如何使用mongosh在MongoDB中引用兄弟ID且排除该兄弟及父文档?
获取MongoDB中指定文档的兄弟文档(排除自身和父文档)
核心思路
要拿到Child1的兄弟文档,关键是匹配同parent_id + 排除Child1自身 + 排除父文档,下面分两种常用方法实现:
方法一:分步查询(简单直接)
假设你的集合中文档结构类似这样:
// 子文档示例(Child1/Child2/Child3) { _id: ObjectId("xxx"), parent_id: ObjectId("parent_xxx"), name: "Child1", type: "child" // 用type区分父子文档,可选 } // 父文档示例 { _id: ObjectId("parent_xxx"), name: "Parent", type: "parent" // 可选 }
- 先获取Child1的父ID和自身ID:
const child1 = db.yourCollection.findOne({ _id: ObjectId("child1的ID") }); const targetParentId = child1.parent_id; const excludeChildId = child1._id;
- 执行查询,过滤出符合条件的兄弟文档:
// 如果用type字段区分父子 db.yourCollection.find({ parent_id: targetParentId, _id: { $ne: excludeChildId }, // 排除Child1自身 type: "child" // 确保只查子文档,排除父文档 }) // 如果父文档没有parent_id字段,直接用这个条件排除 db.yourCollection.find({ parent_id: targetParentId, _id: { $ne: excludeChildId } })
方法二:聚合管道一步完成
不需要单独查询Child1,直接在聚合流程里完成关联和过滤:
db.yourCollection.aggregate([ // 定位到Child1文档,拿到它的parent_id { $match: { _id: ObjectId("child1的ID") } }, // 根据parent_id关联所有同父级的文档 { $lookup: { from: "yourCollection", // 替换成你的集合名 localField: "parent_id", foreignField: "parent_id", as: "siblingDocs" } }, // 展开关联得到的数组 { $unwind: "$siblingDocs" }, // 过滤掉Child1自身和父文档 { $match: { "siblingDocs._id": { $ne: ObjectId("child1的ID") }, "siblingDocs.type": "child" // 或者用"parent_id": { $exists: true }区分 } }, // 只保留兄弟文档的内容 { $replaceRoot: { newRoot: "$siblingDocs" } } ])
你之前查询包含Child1的原因
你只匹配了相同的parent_id,但没加上_id: { $ne: Child1的ID }这个条件,补上之后就能排除自身了。另外要注意区分父文档,避免把父级也查出来。
内容的提问来源于stack exchange,提问作者Stack_monster
相关产品推荐
相关产品推荐

