Insert field with array size in mongo

后端 未结 3 640
遇见更好的自我
遇见更好的自我 2021-01-12 21:20

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 fiel

3条回答
  •  时光说笑
    2021-01-12 21:39

    You could initialise a Bulk() operations builder to update the document in a loop as follows:

    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(); }
    

提交回复
热议问题