如何合并 MongoDB 中两个集合的数据

How to merge data from two collections in 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 集合中为每个值获取 nameAndSurnamearrayOfImages[0] 值,即 [=22= 中的用户] 这样响应就可以是:

[{'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 一样加入,根文档中的所有字段所以添加展开和替换根以合并到 1 个文档中。

查询

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