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

标签 mongodb mongodb-query aggregation-framework

这个问题在这里已经有了答案:





$lookup on ObjectId's in an array

(6 个回答)


4年前关闭。




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

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

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

这是我得到上述结果的方式:
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"
         }
      ],
   }
]

最佳答案

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

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"}}}
               ]);

希望我的代码有用

关于MongoDB:如何在数组中查找字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42263299/

相关文章:

javascript - MongoDB 数组与对象

javascript - MongoDB( Mongoose )集合中特定 ObjectID 的聚合计数实例

mongodb - 是否有一个查询可以连接深层子列表?

node.js - 使用 MongoDB 进行数据分区

java - 将操作分为两个级别,每个级别都有一个元素-数组关联

php - MongoDate toDateTime() 函数没有定义?

javascript - 如何将变量传递给 Mongoose "findByIdAndUpdate"

mongodb - 使用 DBRef 查询 MongoDB

node.js - Mongodb 聚合管道使用 $lookup 从数组返回多个字段

以 id 为键的 MongoDB 组和求和