【问题标题】:MongoDB: how to $lookup a field in an array? [duplicate]MongoDB:如何 $lookup 数组中的字段? [复制]
【发布时间】:2017-07-04 22:27:13
【问题描述】:

我正在尝试检索文档中嵌入数组的一些查找数据。以下是数据示例:

[
   {
      "_id": "58a4fa0e24180825b05e14e9",
      "user_id": "589cf6511b94281f34617a13",
      "user": {
         "firstname": "John",
         "lastname": "Doe"
      },
      "stages": [
         {
            "user_id": "589cf6511b94281f34617a13"
         },
         {
            "user_id": "589cf6511b94281f346343c3"
         }
      ],
   }
]

如您所见,stages 是一个数组,仅包含 user_id 字段。它们指向另一个名为users 的集合中的_id 字段。

这是我得到上述结果的方式:

db.collection('things').aggregate([{
        $match: finder
    },
    {
        $lookup: {
            from: 'users',
            localField: 'user_id',
            foreignField: '_id',
            as: 'user'
        }
    },
    {
        $unwind: '$user'
    }
]);

现在,这很简单:选择记录,user 字段用$lookup 查找。但是我怎样才能对stages 的元素做同样的事情呢?期望的结果是这样的:

[
   {
      "_id": "58a4fa0e24180825b05e14e9",
      "user_id": "589cf6511b94281f34617a13",
      "user": {
         "firstname": "John",
         "lastname": "Doe"
      },

      "stages": [
         {
            "user_id": "589cf6511b94281f34617a13",
            "firstname": "John",
            "lastname": "Doe"
         },
         {
            "user_id": "589cf6511b94281f346343c3"
            "firstname": "Jane",
            "lastname": "Doe"
         }
      ],
   }
]

【问题讨论】:

    标签: mongodb mongodb-query aggregation-framework


    【解决方案1】:

    我相信您缺少的是阶段中的放松和之后的集体通话。我测试了以下代码并得到了类似的结果:

    db.collection('things').aggregate([
                   { $match: finder },
                   { $lookup: {  from: 'users',
                                 localField: 'user_id',
                                  foreignField: '_id',
                                  as: 'user'
                               }
                   },
                   { $unwind: '$stages' },
                   {$lookup : {from : 'users', localField: 'stages.user_id', foreignField: '_id', as : 'stages'}},
                   {$group : { _id: '$_id', userId: "$userId",..., stages: {$push : "$stages"}}}
                   ]);
    

    希望我的代码有用

    【讨论】:

    • 它现在说:“字段 user_id 必须是一个累加器对象”。
    • 我的错,请在要提取的字段前加一个$。比如 {_id: '$_id', userId: "$user_id"...
    • 不,还是一样。
    猜你喜欢
    • 2018-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-06
    • 1970-01-01
    • 1970-01-01
    • 2020-05-26
    • 1970-01-01
    相关资源
    最近更新 更多