所以我想找出这个人的合伙人的名字。我的数据如下:
{
_id: objectId,
first_name: string,
last_name: string,
partners: [objectId]
}我尝试过这个聚合/查找,但是它返回了不正确的结果。
module.exports.getUserPartners = function( user_id, callback ) {
const query = [
{
$unwind: "$partners"
},
{
$lookup: {
from: "people",
localField: "partners",
foreignField: "_id",
as: "people_partners"
}
},
{
$match: { "_id": user_id }
},
{
$project: {
first_name: 1,
last_name: 1
}
}
];
People.aggregate( query, callback );
}如果我的数据如下所示:(我将'123‘作为user_id传递)
{
_id: '123',
first_name: "bob",
last_name: "smith",
partners: ['234','345']
},{
_id: '234',
first_name: "sally",
last_name: "smartypants",
partners: ['789']
},{
_id: '345',
first_name: "martin",
last_name: "tall",
partners: []
}我从上面的聚合查找中得到以下结果:
[{
_id: '123',
first_name: "bob",
last_name: "smith"
},{
_id: '123',
first_name: "bob",
last_name: "smith"
}]当我期待这些结果时:
[{
_id: '234',
first_name: "sally",
last_name: "smartypants"
},{
_id: '345',
first_name: "martin",
last_name: "tall"
}]*注-我根据推荐表单docs和本文$unwind添加了https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/#unwind-example
发布于 2018-09-30 05:17:28
请检查此aggregate查询。看上去很复杂。
db.getCollection('people').aggregate([
{$match : { "_id" : "123"} },
{
$unwind:
{
path:"$partners",
preserveNullAndEmptyArrays: true
}
},
{
$lookup: {
from: "people",
localField: "partners",
foreignField: "_id",
as: "people_partners"
}
},
{
$unwind:
{
path:"$people_partners",
preserveNullAndEmptyArrays: false
}
},
{
$project: {
_id : '$people_partners._id',
first_name : '$people_partners.first_name',
last_name : '$people_partners.last_name',
}
}
])https://stackoverflow.com/questions/52573884
复制相似问题