在mongo中插入具有数组大小的字段

use*_*983 5 mongodb mongodb-query aggregation-framework

我在mongodb中有一个文档,其中包含一些数组。现在,我需要一个包含此数组的大量项目的字段。因此,我需要更新添加此字段的文档。我只是简单地认为这可以工作:

db.myDocument.update({
     "itemsTotal": {
         $exists: false
     },
     "items": {
         $exists: true
     }
 }, {
     $set: {
         itemsTotal: {
             $size: "$items"
         }
     }
 }, {
 multi: true
 })
Run Code Online (Sandbox Code Playgroud)

但是它以“ not okForStorage”完成。我也尝试进行聚合,但是会引发异常:

"errmsg" : "exception: invalid operator '$size'",
"code" : 15999,
"ok" : 0
Run Code Online (Sandbox Code Playgroud)

什么是最佳解决方案,我做错了什么?我开始考虑编写用于计算总数的Java工具并使用它更新文档。

chr*_*dam 1

您可以初始化Bulk()操作构建器以循环更新文档,如下所示:

var bulk = db.collection.initializeOrderedBulkOp(),   
    count = 0;

db.collection.find("itemsTotal": { "$exists": false },
     "items": {
         $exists: true
     }
).forEach(function(doc) { 
    var items_size = doc.items.length;
    bulk.find({ "_id": doc._id }).updateOne({ 
        "$set": { "itemsTotal": items_size }
    });
    count++;
    if (count % 100 == 0) {
        bulk.execute();
        bulk = db.collection.initializeUnorderedBulkOp();
    }
});

if (count % 100 != 0) { bulk.execute(); }
Run Code Online (Sandbox Code Playgroud)