【问题标题】:How to combine multiple collections and merge the joined documents into a single document如何组合多个集合并将连接的文档合并为单个文档
【发布时间】:2018-03-15 13:59:46
【问题描述】:

这是问题所在,我无法得到以下结果。请查看那段 json 并帮助我。

这是我的数据:

[
  {
    "user_id": "65asdfksadjfk3u4",
    "lat": 23.4343,
    "long": 15.2382 
  }
]

目前我的结果是:

[
  {
    "_id": "65asdfksadjfk3u4",
    "name": "Srini",
    "age": 26,
    "some other key": "some other values"
  }
]

我需要从user_id 获取集合并将其添加到同一个数组对象中。您可以注意到,在我当前的结果中,lat 和 long 都被删除了。

[
  {
     "_id": "65asdfksadjfk3u4",
     "name": "Srini",
     "age": 26,
     "some other keys": "some other values",
     "lat": 23.4343,
     "long": 15.2382 
  }
]

【问题讨论】:

    标签: mongodb mongodb-query aggregation-framework


    【解决方案1】:

    您可以附加 $lookup 阶段以通过 user_id 字段将当前管道结果与 users 集合连接起来,然后在中使用 $mergeObjects $replaceRoot 用于合并来自users 的连接文档和当前结果:

    db.collection.aggregate([
        /* current pipeline here */
        { "$lookup": {
                "from": "users",
                "localField": "_id",
                "foreignField": "user_id",
                "as": "user"
        } },
        { "$replaceRoot": { 
            "newRoot": { 
                "$mergeObjects": [ 
                    { "$arrayElemAt": [ "$user", 0 ] }, 
                    "$$ROOT" 
                 ] 
            } 
        } },
        { "$project": { "user": 0, "user_id": 0 } }    
    ]);
    

    【讨论】:

    • $mergeObjects 仅适用于 mongodb v3.6 及更高版本。这是要记住的一件事。由于我们使用的是 mlab,因此它不支持 v3.6。
    猜你喜欢
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-23
    相关资源
    最近更新 更多