MongoDB:如何在数组中查找字段?

Tam*_*gár 3 mongodb mongodb-query aggregation-framework

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

[
   {
      "_id": "58a4fa0e24180825b05e14e9",
      "user_id": "589cf6511b94281f34617a13",
      "user": {
         "firstname": "John",
         "lastname": "Doe"
      },
      "stages": [
         {
            "user_id": "589cf6511b94281f34617a13"
         },
         {
            "user_id": "589cf6511b94281f346343c3"
         }
      ],
   }
]
Run Code Online (Sandbox Code Playgroud)

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

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

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

现在,这非常简单:选择记录,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"
         }
      ],
   }
]
Run Code Online (Sandbox Code Playgroud)

Isr*_*inc 5

我相信你缺少的是在舞台上的放松和之后的群聊。我测试了以下代码并得到了类似的结果:

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"}}}
               ]);
Run Code Online (Sandbox Code Playgroud)

希望我的代码有用