繁体   English   中英

如何在具有相同值的相同字段名称上连接两个 MongoDB Collections?

[英]How to Join Two MongoDB Collections on the Same Field Name with the same value?

我的 MongoDB 数据库中有两个 collections,我想在搜索数字时加入相同的字段值。 这是我的 collections 结构:

第一个集合的名称是用户:

{
user_id : "1234",
phone_number: "+9600000000000"
}

第二个集合的名称是 users_info:

{
name : "John Smith",
phone_number: "+9600000000000",
age: "45",
address: "DC"
}

我想创建一个连接这两个 collections 的查询,其中phone_number等于一个值。 结果类似于以下内容:

{
user_id : "1234",
name :"John Smith",
phone_number: "+9600000000000",
age: "45",
address: "DC"
}

这是一种方法。

db.users.aggregate([
  {
    "$match": {
      "phone_number": "+9600000000000"
    }
  },
  {
    "$lookup": {
      "from": "users_info",
      "localField": "phone_number",
      "foreignField": "phone_number",
      "as": "user_info",
      "pipeline": [
        {"$unset": "_id"}
      ]
    }
  },
  {
    "$replaceWith": {
      "$mergeObjects": [
        "$$ROOT",
        {"$first": "$user_info"}
      ]
    }
  },
  {
    "$unset": ["_id", "user_info"]
  }
])

mongoplayground.net上试用。

如果您的 MongoDB 服务器版本在"$unset"可用时低于 4.2,您可以使用"$project" ,如下所示。

db.users.aggregate([
  {
    "$match": {
      "phone_number": "+9600000000000"
    }
  },
  {
    "$lookup": {
      "from": "users_info",
      "localField": "phone_number",
      "foreignField": "phone_number",
      "as": "user_info",
      "pipeline": [
        {
          "$project": {
            "_id": 0
          }
        }
      ]
    }
  },
  {
    "$replaceWith": {
      "$mergeObjects": [
        "$$ROOT",
        {"$first": "$user_info"}
      ]
    }
  },
  {
    "$project": {
      "_id": 0,
      "user_info": 0
    }
  }
])

mongoplayground.net上试用。

暂无
暂无

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

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