我想找出类型为“ 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"
}
它应该仅以type =“ Normal”和atr.value =“ Foo Bar”(用于atr.key =“ UDSP”)和desc =“ Foo Bar”的形式给出结果作为Ist对象
答案 0 :(得分:0)
您可以使用此查询。首先根据条件为匹配的文档添加一个字段,并根据添加的字段进行过滤
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 } }
])