MongoDB如何从对象数组中查询单个文档?
实现MongoDB数组内指定子文档的单独查询结果
当然可以实现,以下几种方法都能直接返回你需要的单个子文档结构:
方法一:使用聚合管道(推荐,一步到位)
通过聚合管道的多阶段处理,直接将目标子文档作为根文档返回:
db.collection.aggregate([ // 定位到包含目标子文档的主文档 { $match: { accountId: "182092109" } }, // 拆分documents数组,每个子文档独立成文档 { $unwind: "$documents" }, // 筛选出idDocuments为"0001"的子文档 { $match: { "documents.idDocuments": "0001" } }, // 将子文档提升为根文档,去除外层结构 { $replaceRoot: { newRoot: "$documents" } } ])
方法二:用$filter+$arrayElemAt定位子文档
适合不需要拆分整个数组的场景,通过数组操作直接提取目标元素:
db.collection.aggregate([ { $match: { accountId: "182092109" } }, { $project: { targetDoc: { $arrayElemAt: [ // 筛选数组中符合条件的元素 { $filter: { input: "$documents", cond: { $eq: ["$$this.idDocuments", "0001"] } } }, 0 // 取筛选结果的第一个元素(这里只会有一个匹配项) ] }, _id: 0 } }, // 将提取的子文档作为根返回 { $replaceRoot: { newRoot: "$targetDoc" } } ])
方法三:基础find查询(需客户端额外处理)
如果用基础find查询,会返回包含父文档结构的结果,需要客户端从数组中取出目标元素:
db.collection.find( { accountId: "182092109", "documents.idDocuments": "0001" }, { "documents.$": 1, _id: 0 } )
该查询返回结果为{ documents: [ { idDocuments:"0001", ... } ] },需要客户端进一步提取documents[0]得到目标结构。
内容的提问来源于stack exchange,提问作者fnnqmrn
相关产品推荐
相关产品推荐

