慕田峪4524236
这应该可以解决问题(https://mongoplayground.net/p/Iu53HQbi7Me):测试数据:// users collection[ { _id: ObjectId("5a934e000102030405000001"), name: "John Doe" }, { _id: ObjectId("5a934e000102030405000002"), name: "Jane Roe" }]// groups collection[ { _id: 100, name: "A Group", members: [ ObjectId("5a934e000102030405000001"), ObjectId("5a934e000102030405000002") ] }]查询:db.users.aggregate([// join the two collections { $lookup: { "from": "groups", "localField": "_id", "foreignField": "members", "as": "membersInfo" } },// unwind the membersInfo array { $unwind: "$membersInfo" }, { $project: { "_id": { $cond: { "if": { $in: [ "$_id", "$membersInfo.members" // replace _id field based on the members ] }, "then": "$_id", "else": "No group" } }, "name": 1, // mantain this field "_group": "$membersInfo._id" // create _group field using the _id of groups collection } }])结果:[ { "_group": 100, "_id": ObjectId("5a934e000102030405000001"), "name": "John Doe" }, { "_group": 100, "_id": ObjectId("5a934e000102030405000002"), "name": "Jane Roe" }]