递归Mongo查找

时间:2018-09-30 01:40:21

标签: mongodb aggregate

因此,我想查找当前人的合伙人的姓名。 我的数据如下:

{
    _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

1 个答案:

答案 0 :(得分:1)

请检查此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',

            }
        }
    ])