如何在MongoDB中合并来自两个集合的数据 [英] How to merge data from two collections in MongoDB

查看:22
本文介绍了如何在MongoDB中合并来自两个集合的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的需要帮助解决我当前的问题。

问题:如何合并两个集合中的数据?

第一个集合称为users,其中每个文档保存关于一个用户的信息。此集合中JSON格式的文档的一个示例:

    {
        "_id": ObjectId("userId1"),
        "nameAndSurname": "Name 1",
        "arrayOfImages": ["wwww.urlToImage1.jpeg"],
        "favouritePlayer" : "Monfils",
        "sport" : "Tennis",
        "isProfileBlocked" : false
    }
第二个集合称为user_relations,其中每个文档都包含有关users集合中的某个用户拥有的朋友的信息。此集合中JSON格式的文档的一个示例:

    {
        "_id": ObjectId("someRandomString"),
        "userId": "userId1",
        "friendsArray": [
        {
            "userId" : "userId2",
            "lastTimestamp": 19236752642,
            "message": "Hellooo"
        },
        {
            "userId" : "userId3",
            "lastTimestamp": 12236752342,
            "message": "Yeah",
        },
        ]
    }

我有一个如下所示的Python查询:

db.user_relations.aggregate([
  {
    "$match": {
      "userId": "userId1"
    }
  },
  {
    "$unwind": {
      "path": "$friendsArray"
    }
  },
  {
    "$sort": {
      "friendsArray.lastTimestamp": 1
    }
  },
  {
    "$limit": 10
  },
  {
    "$replaceRoot": {
      "newRoot": "$friendsArray"
    }
  }
])

我运行该查询时的响应如下所示:

[{'userId': 'userId2', 'lastTimetamp': 19236752642, 'message': 'Yeah'}, {'userId': 'userId3', 'lastTimestamp': 12236752342, 'message': 'Hellooo'}]

现在我要做的是修改此查询,以便可以从users集合中为friendsArray中的每个值(即用户)获取nameAndSurnamearrayOfImages[0]值,以便响应可以是:

[{'userId': 'userId2', 'nameAndSurname : 'Name 2', 'pictureUrl' : 'wwww.urlToImage2.jpeg', 'lastTimestamp': 19236752642, 'message': 'Yeah'}, {'userId': 'userId3', 'nameAndSurname : 'Name 3', 'pictureUrl' : 'wwww.urlToImage3.jpeg', 'lastTimestamp': 12236752342, 'message': 'Hellooo'}]

感谢您抽出时间!

推荐答案

Test code here

您想要$lookup,但您想要的是类似SQL Like Join,这样根文档中的所有字段都会添加展开和替换根以合并到一个文档中。

查询

db.user_relations.aggregate([
  {
    "$match": {
      "$expr": {
        "$eq": [
          "$userId",
          "userId1"
        ]
      }
    }
  },
  {
    "$unwind": {
      "path": "$friendsArray"
    }
  },
  {
    "$sort": {
      "friendsArray.lastTimeStamp": 1
    }
  },
  {
    "$limit": 10
  },
  {
    "$replaceRoot": {
      "newRoot": "$friendsArray"
    }
  },
  {
    "$lookup": {
      "from": "users",
      "localField": "userId",
      "foreignField": "_id",
      "as": "joined__"
    }
  },
  {
    "$unwind": {
      "path": "$joined__"
    }
  },
  {
    "$replaceRoot": {
      "newRoot": {
        "$mergeObjects": [
          "$joined__",
          "$$ROOT"
        ]
      }
    }
  },
  {
    "$project": {
      "joined__": 0
    }
  }
])

这篇关于如何在MongoDB中合并来自两个集合的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆