在mongo中插入具有数组大小的字段 [英] Insert field with array size in mongo

查看:73
本文介绍了在mongo中插入具有数组大小的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在mongodb中有一个文档,其中包含一些数组.现在,我需要一个包含此数组的大量项目的字段.因此,我需要更新添加此字段的文档. 我只是以为这会起作用:

I have a documents in mongodb, containing some array. Now I need to have a field containing a quantity of items of this array. So I need to update documents adding this field. Simply I thought this will work:

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

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

But it completes with "not okForStorage". Also I tried to make an aggregation, but it throws exception:

"errmsg" : "exception: invalid operator '$size'",
"code" : 15999,
"ok" : 0

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

What is a best solution and what I do wrong? I'm starting to think about writing java tool for calculation totals and updating documents with it.

推荐答案

您可以使用 .aggregate() 方法 $project 您的文档并返回 $size 项数组.之后,您需要使用 $set 使用批量" 操作可最大程度地提高文档的itemTotal字段.

You can use the .aggregate() method to $project your documents and return the $size of the items array. After that you will need to loop through your aggregation result using the .forEach loop and $set the itemTotal field for your document using "Bulk" operation for maximum efficiency.

var bulkOp = db.myDocument.initializeUnorderedBulkOp(); 
var count = 0;

db.myDocument.aggregate([
    { "$match": { 
        "itemsTotal": { "$exists": false } ,
        "items": { "$exists": true }
    }}, 
    { "$project": { "itemsTotal": { "$size": "$items" } } }
]).forEach(function(doc) { 
        bulkOp.find({ "_id": doc._id }).updateOne({ 
            "$set": { "itemsTotal": doc.itemsTotal }
        });
        count++;
        if (count % 200 === 0) {
            // Execute per 200 operations and re-init
            bulkOp.execute();
            bulkOp = db.myDocument.initializeUnorderedBulkOp();
        }
})

// Clean up queues
if (count > 0) { 
    bulkOp.execute();
}

这篇关于在mongo中插入具有数组大小的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆