Home > Mobile >  Aggregate Query on nested documents MongoDB
Aggregate Query on nested documents MongoDB

Time:09-21

I am completely new to MongoDB. I am facing one issue.

I have a collection with nested documents, below is the sample for that:

{
  "_id":ObjectId("933fc7711f8fd62e834e78b"),
  "date":"12/11/2021",
  "member":"sample",
  details:[{
    "markId":{
        "key":"Mark",
        "value":"er45"
       },
"contact":{
        "key":"Contact",
         "value":"8769056"
      }
},{
    "markId":{
        "key":"Mark",
         "value":"er46"
    },
    "contact":{
         "key":"Contact",
         "value":"90969056"
       }
}]

}

Now I have written the query below:

db.collection.aggregate([
{$match:{"details.markId.value":"er45"}},
{$addFields:{firstDetails:{$arrayElemAt:["$details",0]}}},
{$unset:'details'},
{
$project:{
_id:0,date:1,member:1,
markid:'$firstDetails.markid.value',
contact:'$firstDetails.contact.value',
}
}]).toArray()

I want to get the document based on the details.markId.value.But it is returning an empty array.

CodePudding user response:

You have a typo in markId.

db.collection.aggregate([
{$match:{"details.markId.value":"er45"}},
{$addFields:{firstDetails:{$arrayElemAt:["$details",0]}}},
{$unset:'details'},
{
$project:{
_id:0,date:1,member:1,
markid:"$firstDetails.markId.value",
contact:"$firstDetails.contact.value",
}
}]).toArray();

[
    {
        "date" : "12/11/2021",
        "member" : "sample",
        "markid" : "er45",
        "contact" : "8769056"
    }
]
  • Related