简体   繁体   English

在 mongodb 中加入两个集合

[英]Join two collection in mongodb

I'm new in mongodb.我是 mongodb 的新手。 Could you please tell me how to perform join operation in this.您能否告诉我如何在此执行连接操作。 I've two collection:我有两个收藏:

Collection 1 ("user")集合 1(“用户”)

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

Collection 2 ("square")集合 2(“方形”)

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

Now I want to retrieve the data from collection 2 is like this.现在我想从集合 2 中检索数据是这样的。 Expected output:预期输出:

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

Thanks in advance :)提前致谢 :)

Here's one way to do it.这是一种方法。

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

Try it on mongoplayground.net .mongoplayground.net上试试。

You can keep the first documentid (_id) in the second document as userId for refrence and after that, you can use the join feature supported by MongoDB 3.2 and later versions.您可以将第二个文档中的第一个 documentid (_id) 保留为 userId 以供参考,之后您可以使用 MongoDB 3.2 及更高版本支持的 join 功能。 You can use joins by using an aggregate query.您可以使用聚合查询来使用联接。 You can do it using the below example :您可以使用以下示例执行此操作:

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

The Result will be结果将是

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

Cheers干杯

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM