【问题标题】:How to aggregate two collections in Mongoose/MongoDB?如何在 Mongoose/MongoDB 中聚合两个集合?
【发布时间】:2020-01-31 03:43:20
【问题描述】:

在我的学习服务器上。我有两个与用户和他们的比赛合集。 Races 具有userId 属性,以便了解是什么用户进行了这场比赛。我需要合并所有用户和所有种族的对象。

我收集了一些用户:

[
    {
        "_id": "5d938ec8b17e522018e327db",
        "name": "max",
        "surname": "buinevich",
        "username": "axe",
        "__v": 0
    }
]

和种族集合:

[
    {
        "_id": "5d93ac4c7076dc212ce187d6",
        "userId": "5d938ec8b17e522018e327db",
        "stageId": "5d939e16d4e51d2eac81827d",
        "title": "test race",
        "time": 33,
        "description": "test desc",
        "__v": 0
    }
]

所以我需要让所有用户参加适当的比赛才能获得如下结果:

[
    {
        "_id": "5d938ec8b17e522018e327db",
        "name": "max",
        "surname": "buinevich",
        "username": "axe",
        "races": [{
                    "_id": "5d93ac4c7076dc212ce187d6",
                    "userId": "5d938ec8b17e522018e327db",
                    "stageId": "5d939e16d4e51d2eac81827d",
                    "title": "test race",
                    "time": 33,
                    "description": "test desc",
                    "__v": 0
                }]
        "__v": 0
    }
]

我不想在集合模式中使用参考。也许像猫鼬聚合之类的东西。

【问题讨论】:

    标签: node.js mongodb mongoose aggregation-framework


    【解决方案1】:

    如果在 mongoose schemas 中不使用 refs(尽管推荐),因为 populate 非常方便地生成分层文档。

    选项是使用原生聚合管道 $lookup,它本质上是在连接集合上执行(类似于SQL 中的LEFT JOIN),以在数组字段中填充文档。

    聚合查询:

    db.usersCollection.aggregate([
      {
        $lookup: {
          from: "racesCollection",
          localField: "_id",
          foreignField: "userId",
          as: "races"
        }
      }
    ]).pretty();
    

    Mongoose 模型聚合查询如下所示:

    UserModel.aggregate.lookup({
      from: "Races", //or Races.collection.name
      localField: "_id",
      foreignField: "userId",
      as: "races"
    });
    

    输出:

    {
        "_id" : ObjectId("5d938ec8b17e522018e327db"),
        "name" : "max",
        "surname" : "buinevich",
        "username" : "axe",
        "__v" : 0,
        "races" : [
            {
                "_id" : ObjectId("5d93ac4c7076dc212ce187d6"),
                "userId" : ObjectId("5d938ec8b17e522018e327db"),
                "stageId" : ObjectId("5d939e16d4e51d2eac81827d"),
                "title" : "test race",
                "time" : 33,
                "description" : "test desc",
                "__v" : 0
            }
        ]
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-11-10
      • 2017-07-13
      • 2020-06-13
      • 1970-01-01
      • 2023-03-28
      • 2017-11-10
      • 2018-03-06
      相关资源
      最近更新 更多