首页 > 解决方案 > 用于查找与特定数组键值匹配的字段的 Mongo 查询

问题描述

我想找出 type="Normal" 和 desc==atr.value 的元素(特定键 atr.key="UDSP" 的 atr.value)。我使用的是 mongo 3.0.4,所以不能使用 $expr。下面是数据集:

JSON

   "_id":ObjectId("12345"),
   "desc":"Foo Bar",
   "type":"Normal",
   "atr":[
      {
         "key":"DSP",
         "value":"Goo Bar"
      },
      {
         "key":"UDSP",
         "value":"Foo Bar"
      }
   ],
   "prod":"yes"
}
{
   "_id":ObjectId("12347"),
   "desc":"Boo Bar",
   "type":"Normal",
   "atr":[
      {
         "key":"DSP",
         "value":"Goo Bar"
      },
      {
         "key":"UDSP",
         "value":"Foo Bar"
      }
   ],
   "prod":"yes"
}

它应该将结果作为 Ist 对象仅作为 type="Normal" 和 atr.value="Foo Bar"(for atr.key="UDSP") 和 desc="Foo Bar"

标签: mongodbmongodb-queryaggregation-framework

解决方案


您可以使用此查询。首先根据条件为匹配的文档添加一个字段,然后根据添加的字段进行过滤

db.test.aggregate([ 
    { $match: { type: "Normal", "atr.key":"UDSP" }},
    { $addFields:{ 
        isDocMatched: { 
          $anyElementTrue: { 
              $map:{
                  input: "$atr",
                  as: "grade",
                  in: { $eq: [ "$$grade.value", "$desc" ] }
              }
          }
       }
    }},
    { $match: { isDocMatched: true } }  
])

推荐阅读