Home > Software engineering >  MongoDB returning two array while using alias
MongoDB returning two array while using alias

Time:10-21

I am a json in mongodb. The structure is below --

{id:1,name:sample,user:[{data_alias:ex, value:efg}]}

Now I want the the data_alias to be data after mongodb returns the result.

When I am using below query --

db.coll.find({"id":"1"}, {"data": "$user.data_alias","_id": 0,"value":1})

Now it is retuning data like --

"user" : [ { "value" : "efg", }, ], "data" : [ "ex", ]

But I want the returning value should be like --

"user" : [ { "name" : "sample", "data":"ex" }, ]

Also I have tried with aggregate function

db.colls.aggregate([
     { $match: {"id":"1"} },
   { "$project": {
      "_id": 0,
      "data": "$user.data_alias"
   }}
]);

Both the queries returning same result.

CodePudding user response:

Use $arrayElemAt to access the first element of your array.

db.collection.find({
  "id": "1"
},
{
  _id: 0,
  "name": 1,
  "data": {
    $arrayElemAt: [
      "$user.data_alias",
      0
    ]
  }
})

Here is the Mongo playground for your reference.

  • Related