【问题标题】:Trying to create mongoDB collection using below two mongoDB collection based on ID using python尝试使用以下两个基于 ID 的 mongoDB 集合使用 python 创建 mongoDB 集合
【发布时间】:2021-12-29 09:30:28
【问题描述】:

尝试使用以下两个基于 ID 的 mongoDB 集合使用 python 创建 mongoDB 集合

Mongo Collecton ABC:

{
    Id : 1
    ABC_Action : 234
    Name: "Naveen"
    Age : 30
}

MongoDB 集合 DEF:

{
    Id : 1
    Action : 456
    Name: "Manish"
    Age : 33
}

根据 Id 比较 MongoDB 集合 ABC 和 DEF,如果匹配,则从 ABC 获取 ABC_Action,从 DEF 获取其他键值对。

结果:

{
    ABC_Action : 234
    Name : "Manish"
    Age : 33
}

【问题讨论】:

    标签: python mongodb


    【解决方案1】:

    您可以在聚合中使用$lookup 来加入两个集合。

    • $lookup 正在对两个 _id 字段进行连接
    • $addFields 用于取def_objects because $lookup 的第一个元素只返回一个数组
    • $project 从 ABC 或 EDF 集合中获取您想要的字段
    [
      {
        $lookup: {
          from: "DEF",
          let: {
            "abc_id": "$_id",
            
          },
          pipeline: [
            {
              $match: {
                $expr: {
                  $eq: [
                    "$$abc_id",
                    "$_id"
                  ]
                }
              }
            }
          ],
          as: "def_objects"
        }
      },
      {
        "$addFields": {
          "def_objects": {
            "$first": "$def_objects"
          }
        }
      },
      {
        "$project": {
          "_id": 0,
          "ABC_Action": "$ABC_Action",
          "Name": "$def_objects.Name",
          "Age": "$def_objects.Age"
        }
      }
    ]
    

    试试here

    如果要将结果保存到其他集合中,可以使用$out 运算符

    【讨论】:

      猜你喜欢
      • 2012-09-26
      • 1970-01-01
      • 2020-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-20
      • 1970-01-01
      • 2018-08-24
      相关资源
      最近更新 更多