monogdb嵌套数组项完全匹配

时间:2018-08-23 07:39:44

标签: mongodb mongodb-query

我下面有一个集合,我想要的是提取与Tag="dolore"完全匹配的项目,我尝试了不同的方法,但是如果有任何嵌入元素的标签为{{ 1}}

dolore

1 个答案:

答案 0 :(得分:0)

如果希望仅获取匹配的嵌入文档,则您将拥有$unwind$match$group来反转$unwind。像这样:

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"
            }
         }
      }
   },

])

输出:

{
    "_id" : 123.0,
    "vendor" : "ut",
    "boxes" : [ 
        {
            "boxRef" : 321.0,
            "items" : [ 
                {
                    "Tag" : "dolore"
                }
            ]
        }
    ]
}