【发布时间】:2018-09-30 13:17:28
【问题描述】:
所以我想找到当前人的合伙人的名字。 我的数据如下所示:
{
_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"
}]
*注意 - 我根据推荐表格文档和这篇文章添加了 $unwind https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/#unwind-example
【问题讨论】:
-
查看聚合和
$lookup -
$lookup 尝试的结果见上文
-
您发布的收藏与预期结果有何不同?
-
注意名字和ids...预期的结果应该是为伙伴拉取匹配的名字...实际结果是两次返回主要的persons记录(ids在合作伙伴数组)。
-
不要在此处使用
$unwind,在管道的开头使用$match。