【问题标题】:Recursive Mongo Find递归 Mongo 查找
【发布时间】: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

标签: mongodb aggregate


【解决方案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',

            }
        }
    ])

【讨论】:

  • 完美 - 谢谢 - 我明白了......!!奖金
猜你喜欢
  • 2011-04-24
  • 2012-07-17
  • 2015-12-16
  • 2011-05-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多