如何在Mongoose/MongoDB中合并两个集合?

3
在我的学习服务器上,我有两个集合,分别存储着用户和他们的比赛信息。比赛信息集合中有一个"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
    }
]

我不想在集合模式中使用引用(refs)。也许可以尝试使用Mongoose的聚合操作(aggregate)或其他方式。
1个回答

8
如果不在Mongoose模式中使用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
        }
    ]
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接