如何在MongoDB中按索引查询嵌套数组内的指定元素
MongoDB多层嵌套数组指定下标元素提取方案
现有结构如下的MongoDB文档:
{ "tid": 1, "matches": [ { "dord": 1, "matches": [ { "tord": 1, "score": 11 }, { "tord": 2, "score": 12 } ] }, { "dord": 2, "matches": [ { "tord": 1, "score": 21 }, { "tord": 2, "score": 22 } ] } ] }
需要提取路径为matches.1.matches.1的元素,期望返回结果:
{ "tord": 2, "score": 22 }
方案1:聚合管道(全版本兼容)
通过$arrayElemAt算子提取数组指定下标位置的元素,兼容性最好,查询语句如下:
db.collection.aggregate([ // 筛选目标文档,可根据实际业务调整匹配条件 { $match: { tid: 1 } }, // 投影提取目标元素 { $project: { _id: 0, target: { $arrayElemAt: [ { $arrayElemAt: [ "$matches.matches", 1 ] }, 1 ] } } }, // 可选步骤:直接返回元素对象,而非嵌套在target字段中 { $replaceRoot: { newRoot: "$target" } } ])
方案2:MongoDB 4.4+ 简化写法
如果你使用的是4.4及以上版本的MongoDB,可以通过原生下标访问语法简化查询:
db.collection.aggregate([ { $match: { tid: 1 } }, { $project: { _id: 0, tord: { $first: "$matches.1.matches.1.tord" }, score: { $first: "$matches.1.matches.1.score" } } } ])
注意事项
- MongoDB数组下标默认从0开始计数,
matches.1对应外层matches数组的第二个元素,内层matches.1对应该元素内部matches数组的第二个元素,和需求路径完全匹配。 - 如果匹配条件命中多个文档,会返回所有符合条件文档的对应元素,可根据需求增加
limit限制返回条数。
内容的提问来源于stack exchange,提问作者Saurav Pathak
相关产品推荐
相关产品推荐

