如何在MongoDB聚合中实现数组对象的精准多条件匹配
解决MongoDB聚合中数组键值对的精准匹配问题
你的查询之所以出现错误结果,是因为当前写法没有关联attributes数组中key和value的对应关系:每个$match条件只是分别检查数组里是否存在某个元素的key符合要求,同时是否存在某个元素的value符合要求,但这两个条件不需要来自同一个数组元素,所以会匹配到那些其他属性值包含目标字符串的文档。
要确保同时匹配到包含{key:'setCode',value:'qc'}和{key:'code',value:'potions'}的文档,需要用$elemMatch来约束数组元素的键值对关联关系,正确的聚合查询写法如下:
写法一:直接在$match中使用多个$elemMatch
db.getCollection('cards').aggregate([ { "$match": { "attributes": { "$elemMatch": { "key": "setCode", "value": "qc" } }, "attributes": { "$elemMatch": { "key": "code", "value": "potions" } } } } ]);
写法二:用$and明确包裹多个匹配条件(效果和写法一一致)
db.getCollection('cards').aggregate([ { "$match": { "$and": [ { "attributes": { "$elemMatch": { "key": "setCode", "value": "qc" } } }, { "attributes": { "$elemMatch": { "key": "code", "value": "potions" } } } ] } } ]);
核心原理
$elemMatch的作用是强制MongoDB在数组中寻找同一个元素,同时满足指定的所有条件。这样每个$elemMatch都会精准匹配到数组中对应的键值对,两个条件同时生效时,就只会返回同时包含这两组目标键值对的文档。
内容的提问来源于stack exchange,提问作者napfernandes
相关产品推荐
相关产品推荐

