【问题标题】:Combining data from 2 mongoDB collections into 1 document将来自 2 个 mongoDB 集合的数据合并到 1 个文档中
【发布时间】:2021-10-30 08:05:56
【问题描述】:

我想过滤 2 个集合并返回一个文档。

我有 2 个这样建模的 MongoDB 集合

Analytics_Region

    _id:5ecf3445365eca3e58ff57c0,
    type:"city"
    name:"Toronto"
    CSD:"3520005"
    CSDTYPE:"C"
    PR:"35"
    PRNAME:"Ontario"
    geometry:Object
    country:"CAN"
    updatedAt:2021-04-23T18:25:50.774+00:00
    province:"ON"

Analytics_Region_Custom

    _id:5ecbe871d8ab4ab6845c5142
    geometry:Object
    name:"henry12"
    user:5cbdd019b9d9170007d15990
    __v:0

我想按按名称字母顺序输出单个集合

    {
       _id: 5ecbe871d8ab4ab6845c5142,
       name: "henry12",
       type: "custom",
       province: null
    
    },
    {
        _id:5ecf3445365eca3e58ff57c0,
        name:"Toronto"
        type:"city"
        province:"ON",
    }

注意事项:在输出中,我们为 Analytics_Region_custom 中的每个文档添加了一种“自定义”。我们还为每个文档添加了一个“null”省。

到目前为止,我查看了 $lookup(从另一个集合中获取结果),但它似乎无法满足我的需求,因为它在每个文档中添加了一个数组

【问题讨论】:

    标签: mongodb mongoose mongodb-query aggregation-framework pymongo


    【解决方案1】:

    您可以使用$unionWith
    文档将被添加到管道中(不检查重复项),我们将从这些文档中投影字段

    • 如果缺少类型 => 自定义
    • 如果省缺 => null

    *如果这两个有任何错误值,例如false/0/null,则保留旧值(仅在缺少字段时才保留新值)

    Test code here

    db.coll1.aggregate([
      {
        "$unionWith": {
          "coll": "coll2"
        }
      },
      {
        "$project": {
          "_id": "$_id",
          "name": "$name",
          "type": {
            "$cond": [
              {
                "$ne": [
                  {
                    "$type": "$type"
                  },
                  "missing"
                ]
              },
              "$type",
              "custom"
            ]
          },
          "province": {
            "$cond": [
              {
                "$ne": [
                  {
                    "$type": "$province"
                  },
                  "missing"
                ]
              },
              "$province",
              null
            ]
          }
        }
      },
      {
        "$sort": {
          "name": 1      
        }
      }
    ])
    

    【讨论】:

      【解决方案2】:
      • $unionWith 执行两个集合的联合
      • $project 仅投影您想要的字段
      • sort名称字段排序
      db.orders.aggregate([
        {
          $unionWith: "inventory"
        },
        {
          $project: {
            _id: 1,
            name: 1,
            province: { $cond: { if: "$province",  then: "$province", else: null } },
            type: { $cond: { if: "$type", then: "$type", else: "custom" } }
          }
        },
        { 
          $sort: { name: 1 }
        }
      ])
      

      Working example

      【讨论】:

        猜你喜欢
        • 2017-10-17
        • 2017-06-24
        • 1970-01-01
        • 2017-07-13
        • 1970-01-01
        • 2011-08-06
        • 2021-11-04
        相关资源
        最近更新 更多