1

I have a collection as below what I want is to fetch the items that has exact match of Tag="dolore", I tried different ways but I am getting all the elements if any of the embedded element has tag as dolore

{
    "_id" : 123,
    "vendor" : "ut",
    "boxes" : [ 
        {
            "boxRef" : 321,
            "items" : [ 
                {
                    "Tag" : "dolore",

                }, 
                {
                    "Tag" : "irure",

                }, 
                {
                    "Tag" : "labore",

                }
            ]
        }, 
        {
            "boxRef" : 789,
            "items" : [ 
                {
                    "Tag" : "incididunt",

                }, 
                {
                    "Tag" : "magna",

                }, 
                {
                    "Tag" : "laboris",

                }
            ]
        }, 
        {
            "boxRef" : 456,
            "items" : [ 
                {
                    "Tag" : "reprehenderit",

                }, 
                {
                    "Tag" : "reprehenderit",

                }, 
                {
                    "Tag" : "enim",

                }
            ]
        }
    ]
}
dsharew
  • 10,377
  • 6
  • 49
  • 75

1 Answers1

0

If you are expecting to get only the matching embedded documents you have $unwind, $match and then $group to reverse the $unwind. Like this:

db.getCollection('collectionName').aggregate([
   {
      $unwind:"$boxes"
   },
   {
      $unwind:"$boxes.items"
   },
   {
      $match:{
         "boxes.items.Tag":"dolore"
      }
   },
   {
      $group:{
         _id:{
            boxRef:"$boxes.boxRef",
            _id:"$_id"
         },
         vendor:{
            "$first":"$vendor"
         },
         boxRef:{
            "$first":"$boxes.boxRef"
         },
         items:{
            $push:"$boxes.items"
         }
      }
   },
   {
      $group:{
         _id:"$_id._id",
         vendor:{
            "$first":"$vendor"
         },
         boxes:{
            $push:{
               boxRef:"$boxRef",
               items:"$items"
            }
         }
      }
   },

])

Output:

{
    "_id" : 123.0,
    "vendor" : "ut",
    "boxes" : [ 
        {
            "boxRef" : 321.0,
            "items" : [ 
                {
                    "Tag" : "dolore"
                }
            ]
        }
    ]
}
dsharew
  • 10,377
  • 6
  • 49
  • 75