MongoDB聚合查询:匹配对象数组中每个对象的精确组合
MongoDB聚合实现精确匹配数组子对象的产品筛选
你的products集合结构如下,每个产品包含一个variations数组,数组元素是带color和size字段的子文档:
Product { variations [ { color, size } ] }
现有一条示例产品数据:
{ variations: [ { color: "Verde", size: "xxs" }, { color: "Blu", size: "m" } ] }
需求明确:只有当查询的color和size属于同一个variations子对象时,才返回该产品——比如查color: "Verde"+size: "xxs"能拿到产品,查color: "Verde"+size: "m"就没结果。
核心聚合查询方案
用$match阶段搭配$elemMatch操作符,就能精准筛选出符合要求的产品:
比如要查询color: "Verde"且size: "xxs"的产品,执行以下聚合语句:
db.products.aggregate([ { $match: { variations: { $elemMatch: { color: "Verde", size: "xxs" } } } } ])
原理说明
$elemMatch的作用是检查数组中是否存在至少一个子文档同时满足所有指定条件,不会把不同子文档的color和size混在一起匹配:
- 查
color: "Verde"+size: "m"时,数组里没有任何子文档同时具备这两个值,所以无返回结果 - 查
color: "Blu"+size: "m"时,刚好有对应的子文档,所以返回该产品
进阶:只返回匹配的子文档
如果需要在返回结果里只保留符合条件的variations子对象,可以再加个$addFields和$filter阶段:
db.products.aggregate([ { $match: { variations: { $elemMatch: { color: "Verde", size: "xxs" } } } }, { $addFields: { matchedVariations: { $filter: { input: "$variations", cond: { $and: [ { $eq: ["$$this.color", "Verde"] }, { $eq: ["$$this.size", "xxs"] } ] } } } } } ])
执行后,返回的产品会新增matchedVariations字段,里面只存满足条件的子文档。
内容的提问来源于stack exchange,提问作者Tommaso Merlini
相关产品推荐
相关产品推荐

