【问题标题】:Concatenating MongoDB arrays from different collection for same ID连接来自不同集合的相同 ID 的 MongoDB 数组
【发布时间】:2021-01-18 20:14:56
【问题描述】:

我有两个集合 - col1 和 col2 在同一个数据库下。这些集合包含具有两个字段的文档 - _id 和 arr。我正在尝试查找相同 _id 的匹配项,每当找到匹配项时,我想连接两个 arr 数组。

在 col1 我有以下文件

{'_id': 'shalom', 'arr': [1, 2, 3]}

在 col2 我有以下文件

{'_id': 'shalom', 'arr': [4, 5, 6]}

我想在 col1 中创建一个看起来像这样的新文档

{'_id': 'shalom', 'arr': [1, 2, 3, 4, 5, 6]}

到目前为止我所做的(不起作用)是

merge_query = {'into': col1,
                   'on': '_id',
                   'whenMatched': [
                       {'$addFields': {
                           'processed_words': {'$add': ['$arr', '$$new.arr']}}}],
                   'whenNotMatched': 'insert'}
    col2.aggregate([{'$project': project_query},
                                                     {'$merge': merge_query}])

运行时出现以下异常

pymongo.errors.OperationFailure: $add only supports numeric or date types, not array, full error: {'ok'...

所以看起来差不多了,只需要能够支持数组串联即可。

【问题讨论】:

    标签: mongodb concatenation pymongo


    【解决方案1】:

    我已经检查过了并且工作正常。当您加入阵列时,您需要使用$concatArrays。操作$add 用于求和的数字,例如 (1+1=2)

    db.col2.aggregate([
        {
            $merge:{'into': "col1",
           'on': '_id',
           'whenMatched': [
               {'$addFields': {
                   'processed_words': {'$concatArrays': ['$arr', '$$new.arr']}}}],
           'whenNotMatched': 'insert'
        }
        }
    ])
    

    【讨论】:

      【解决方案2】:

      你可以这样使用$concatArrays$setUnion

      首先$lookup 获取另一个集合数组并创建一个名为newArray 的新“辅助”数组。

      这里,$lookup 返回一个数组,因此必须使用$arrayElementAt 来获取第一个(也是唯一的)位置。

      然后使用$concatArrays$setUnion 连接字段并删除“辅助”数组。

      db.coll1.aggregate([
        {
          "$lookup": {
            "from": "coll2",
            "localField": "_id",
            "foreignField": "_id",
            "as": "newArray"
          }
        },
        {
          "$set": {
            "newArray": {
              "$arrayElemAt": [
                "$newArray",
                0
              ]
            }
          }
        },
        {
          "$set": {
            "arr": {
              "$setUnion": [
                "$arr",
                "$newArray.arr"
              ]
            }
          }
        },
        {
          "$project": {
            "newArray": 0
          }
        }
      ])
      

      例如here

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-10-18
        • 1970-01-01
        • 2020-03-03
        • 1970-01-01
        • 1970-01-01
        • 2020-05-31
        • 1970-01-01
        • 2016-05-28
        相关资源
        最近更新 更多