MongoDB特定格式查询需求:过滤后提取指定字段值列表
MongoDB 查询:提取指定数组元素的字段值列表
现有MongoDB文档结构如下:
{ "name": "name", "list": [ { "id": "abcd1234", "obj": { "key": "abc" } }, { "id": "abcd1234", "obj": { "key": "def" } }, { "id": "abcd4321", "obj": { "key": "hij" } } ] }
需求:筛选出包含list.id: "abcd1234"的文档,并提取匹配元素的obj.key值组成列表["abc", "def"]。
方法一:使用$filter+$map聚合(推荐)
通过聚合管道直接处理数组,无需拆分文档,效率更高:
db.collection.aggregate([ // 筛选符合条件的文档 { $match: { "list.id": "abcd1234" } }, // 提取目标字段并生成列表 { $project: { _id: 0, result: { $map: { input: { $filter: { input: "$list", cond: { $eq: ["$$this.id", "abcd1234"] } } }, as: "item", in: "$$item.obj.key" } } } } ])
执行后返回结果:
{ "result": ["abc", "def"] }
方法二:使用$unwind+$group聚合
通过拆分数组再聚合的方式实现,逻辑更直观:
db.collection.aggregate([ { $match: { "list.id": "abcd1234" } }, // 将数组拆分为单个文档 { $unwind: "$list" }, // 筛选数组中id匹配的元素 { $match: { "list.id": "abcd1234" } }, // 聚合所有匹配的key值到数组 { $group: { _id: null, result: { $push: "$list.obj.key" } } }, // 移除_id字段 { $project: { _id: 0 } } ])
执行后返回结果与方法一一致。
内容的提问来源于stack exchange,提问作者Chrome Chrome
相关产品推荐
相关产品推荐

