如何在聚合管道mongodb中使用$update/$set运算符?

anu*_*anu 4 mongodb mongodb-query nosql-aggregation aggregation-framework

我正在尝试根据某些条件更新name我的集合中调用的字段。coll1我首先创建了一个聚合管道,根据我的标准过滤出文档。

var local_filter = { "$or" :[ 
                                          {'fullText': {'$eq': "404 Error"}},
                                          {'fullText': {'$eq': "Unknown Error"}},
                                          {'fullText': {'$eq': "503 Error"}},
                                          {'fullText': {'$eq': "400 Error"}},
                                          {'fullText': {'$eq': "500 Error"}},
                                          {'fullText': {'$eq': "Read timed out"}},
                                          {'fullText': {'$eq': "410 Error"}},
                                          {'fullText': {'$eq': "403 Error"}},
                                          {"fullText": {'$eq':""}},
                              ]}

var foreign_filter= { "$and" :[
                              {'matchingrecords.Text': {'$ne': "404 Error"}},
                              {'matchingrecords.Text': {'$ne': "Unknown Error"}},
                              {'matchingrecords.Text': {'$ne': "503 Error"}},
                              {'matchingrecords.Text': {'$ne': "400 Error"}},
                              {'matchingrecords.Text': {'$ne': "500 Error"}},
                              {'matchingrecords.Text': {'$ne': "Read timed out"}},
                              {'matchingrecords.Text': {'$ne': "410 Error"}},
                              {'matchingrecords.Text': {'$ne': "403 Error"}},
                              {"matchingrecords.Text": {'$ne': ""}},
                              {"matchingrecords.Text": {'$ne':'null'}}
                              ]}

db.coll1.aggregate([
    {$match:local_filter //9474
    },
    {$lookup: {
           from: "coll2",
           localField: "_id",   //from coll1
           foreignField: "_id", //from coll2
           as: "matchingrecords"
         }//4518
    },
    { $match: foreign_filter
    },
    { $match: {matchingrecords: {$ne:[]} }
    },//3645
    {
      $count: "totalCount"
    }
    ])//3645
Run Code Online (Sandbox Code Playgroud)

因此,我现在收到 3645 个coll1需要更新name字段的文档。我尝试过两种方法,均无效:

  1. { $set: { "Name" :将matchingrecords.Text添加} }到上面的管道。这Name实际上是用字符串设置的matchingrecords.Text,而不是它的值。另外,添加$也没有帮助!

  2. 使用Update 聚合,我在子句中传递了聚合管道u

    db.runCommand(
              {
                update: "coll1",
                updates: [
                   {
                     q: { },
                     u: [// You can pass you aggregation pipeline here
                             {$match: local_filter//9474
                              },
                              {$lookup: {
                                     from: "coll2",
                                     localField: "_id",
                                     foreignField: "_id",
                                     as: "matchingrecords"
                                   }//4518
                              },
                              { $match: foreign_filter
                              },
                              { $match: {matchingrecords: {$ne:[]} }
                              },//3645
                              { $set: { "Name" : 'matchingrecords.Text' } }
                         ],
                         multi: true
                       }
                    ],
                    ordered: false,
                    writeConcern: { w: "majority", wtimeout: 5000 }
                 })
Run Code Online (Sandbox Code Playgroud)

它抱怨说$match operator isn't allowed in update!

{ 
    "n" : 0.0, 
    "nModified" : 0.0, 
    "writeErrors" : [
        {
            "index" : 0.0, 
            "code" : 72.0, 
            "errmsg" : "$match is not allowed to be used within an update"
        }
    ], 
    "ok" : 1.0
}
Run Code Online (Sandbox Code Playgroud)

关于如何更新我的 3645 文档有什么建议吗?

有一个简单的技巧!

解决方案(它对我有用!):

  1. 使用coll1,创建一个包含 3645 个文档的新集合。
      db.coll1.aggregate([
        {$match:filter //9474
        },
        {$lookup: {
               from: "coll2",
               localField: "_id",
               foreignField: "_id",
               as: "matchingrecords"
             }//4518
        },
        { $match: foreign_filter
        },
        { $match: {matchingrecords: {$ne:[]} }
        },//3645
        { $unwind: { path: "$matchingrecords", preserveNullAndEmptyArrays: true }
        },
        { $project : <what All fields you Need?>
        },
        { $out: "child_coll1"
        }//get 3645 in the a new collection
Run Code Online (Sandbox Code Playgroud)
  1. 使用coll1,在单独的集合中获取不匹配的文档
   db.coll1.aggregate([
        {$lookup: {
               from: "child_coll1",
               localField: "_id",
               foreignField: "_id",
               as: "matchingrecords"
             }//
        },
        { $match: {matchingrecords: {$eq:[]} }
        },//30944
        { $unwind: { path: "$matchingrecords", preserveNullAndEmptyArrays: true }
        },
        { $out: "child_coll2"
        }//get out 30944 docs other than 3645
    ])
Run Code Online (Sandbox Code Playgroud)
  1. 只需合并 1 和 2 中的新集合
        db.child_coll1.find().forEach(function(doc){
           db.child_coll2.insert(doc); 
        });
Run Code Online (Sandbox Code Playgroud)
  1. 删除除 之外的所有集合child_coll2,您可以将其重命名为coll1

这不是一个优雅的解决方案,只是完成任务的一个技巧!有谁在一个查询中有更好/优雅的解决方案吗?

inv*_*der 6

为什么您的第一个聚合解决方案不起作用?

$set不是聚合管道的有效阶段运算符。

为什么使用更新命令的第二个解决方案不起作用?

Update命令不接受聚合管道运算符。mongo@4.2根据@prasad_ 共享的参考,仅支持几个运算符

那么如何解决这个问题呢?

检查您是否可以用于$replaceRoot您的用例。如果没有,您可以使用以下技巧。

首先,像之前一样从聚合开始,然后添加$addFields阶段,为每个文档添加一个包含您要设置的值的新字段。然后运行另一个更新命令,如下所示

db.coll1.aggregate([
   { 
   // your match queries 
   },
   {
   $addFields: { myNewName: "myvalue" } 
   }
]).toArray().forEach(function(myDoc){
   db.coll1.update({ _id: myDoc.id }, { $set: {Name: myDoc.myNewName } })
})
Run Code Online (Sandbox Code Playgroud)