MongoDB如何使用projection查询嵌套文档中DEBIT类型下的指定字段
解决方案
你可以通过MongoDB聚合管道实现需求,既能筛选出type: "DEBIT"的菜单条目,也能过滤出对应items下key: "Call"的字段,最终返回你需要的结构:
db.你的集合名.aggregate([ // 可选:提前过滤只包含DEBIT类型菜单的文档,提升查询效率 { $match: { "menu.type": "DEBIT" } }, // 过滤menu数组,仅保留type为DEBIT的元素 { $project: { _id: 0, debitMenu: { $filter: { input: "$menu", cond: { $eq: ["$$this.type", "DEBIT"] } } } } }, // 拆分debitMenu数组为单个对象 { $unwind: "$debitMenu" }, // 过滤items数组,仅保留key为Call的元素 { $project: { targetItem: { $filter: { input: "$debitMenu.items", cond: { $eq: ["$$this.key", "Call"] } } } } }, // 拆分targetItem数组为单个对象 { $unwind: "$targetItem" }, // 直接输出key和enabled字段作为顶级结构 { $replaceRoot: { newRoot: "$targetItem" } }, // 可选:明确指定仅返回需要的两个字段 { $project: { key:1, enabled:1 } } ])
效果说明
执行上述查询后,返回的结果和你需要的结构完全一致:
{ "key": "Call", "enabled": true }
如果你不需要拆分为顶级结构,只需要嵌套返回结果,也可以使用更简单的find查询:
db.你的集合名.find( { "menu.type": "DEBIT" }, { _id: 0, "menu": { $elemMatch: { type: "DEBIT" } }, "menu.items": { $elemMatch: { key: "Call" } }, "menu.items.key": 1, "menu.items.enabled": 1 } )
内容的提问来源于stack exchange,提问作者Tamilselvan
相关产品推荐
相关产品推荐

