将来自 2 mongoDB 个集合的数据合并到 1 个文档中

Combining data from 2 mongoDB collections into 1 document

我想筛选 2 个集合和 return 一个文档。

我有 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_自定义

    _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(从另一个集合中获取结果),但它似乎无法满足我的需要,因为它向每个文档添加了一个数组

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

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

*如果这 2 个有任何假值,例如 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      
    }
  }
])
  • $unionWith 执行两个集合的并集
  • $project 仅投影您想要的字段
  • sortname 字段排序
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