在 mongodb 中加入两个集合

Join two collection in mongodb

我是 mongodb 的新人。你能告诉我如何在这方面执行连接操作吗?我有两个合集:

集合 1(“用户”)

{
 _id: "d04d53dc-fb88-433e-a1c5-dd41a68d7655",
 userName: "XYZ User",
 age: 12
}

集合 2(“正方形”)

{
 _id: "ef6f6ac2-a08a-4f68-a63c-0b4a70285427",
 userId: "d04d53dc-fb88-433e-a1c5-dd41a68d7655",
 side: 4,
 area: 16
}

现在我要从collection 2中检索数据是这样的。 预期输出:

{
 _id: "ef6f6ac2-a08a-4f68-a63c-0b4a70285427",
 userId: "d04d53dc-fb88-433e-a1c5-dd41a68d7655",
 userName: "XYZ User",
 side: 4,
 area: 16
}

提前致谢:)

您可以将第二个文档中的第一个documentid(_id)作为userId作为refrence,之后就可以使用MongoDB3.2及以后版本支持的join功能了。您可以通过使用聚合查询来使用联接。 您可以使用以下示例来完成:

    db.user.aggregate([

    // Join with square table
    {
        $lookup:{
            from: "square",       // other table name
            localField: "_id",   // name of user table field
            foreignField: "userId", // name of square table field
            as: "square"         // alias for userinfo table
        }
    },
    {   $unwind:"$user_info" },     // $unwind used for getting data in object or for one record only

     
    // define some conditions here 
    {
        $match:{
            $and:[{"userName" : "XYZ User"}]
        }
    },

    // define which fields are you want to fetch
    {   
        $project:{
            _id: 1,
            userId: "$square.userId",
            userName: 1,
            side: "$square.side",
            area: "$square.area"
        } 
    }
]);

结果将是

     {
      _id: "ef6f6ac2-a08a-4f68-a63c-0b4a70285427",
      userId: "d04d53dc-fb88-433e-a1c5-dd41a68d7655",
      userName: "XYZ User",
      side: 4,
      area: 16
     }

干杯

这是一种方法。

db.square.aggregate([
  {
    "$lookup": {
      "from": "user",
      "localField": "userId",
      "foreignField": "_id",
      "as": "userDoc"
    }
  },
  {
    "$set": {
      "userName": {
        "$first": "$userDoc.userName"
      }
    }
  },
  { "$unset": "userDoc" }
])

mongoplayground.net 上试用。