如何在MongoDB中提取嵌套数组中指定条件的对象
MongoDB嵌套数组提取符合条件对象的查询语句
针对你需要提取Fname为Svelte且chapterName为Chapter 0的嵌套对象需求,提供两种可行的查询方法:
方法一:聚合管道(直接返回目标对象)
使用聚合管道逐步过滤和提取目标数据,最终返回你需要的单个对象:
db.collection.aggregate([ // 筛选出Fname为"Svelte"的文档 { $match: { Fname: "Svelte" } }, // 从data数组中过滤出chapterName匹配的元素 { $project: { targetChapter: { $filter: { input: "$data", cond: { $eq: ["$$this.chapterName", "Chapter 0"] } } }, _id: 0 } }, // 将数组中的单个匹配元素展开 { $unwind: "$targetChapter" }, // 将目标对象设为根文档返回 { $replaceRoot: { newRoot: "$targetChapter" } } ])
方法二:find查询(返回包含目标元素的数组)
如果可以接受返回包含目标元素的数组结构,也可以用$投影操作符:
db.collection.find( { Fname: "Svelte", "data.chapterName": "Chapter 0" }, { "data.$": 1, _id: 0 } )
该查询会返回一个包含data字段的文档,其中data数组仅包含匹配Chapter 0的对象。
内容的提问来源于stack exchange,提问作者Tanmay Chavan
相关产品推荐
相关产品推荐

