Insert field with array size in mongo

后端 未结 3 669
遇见更好的自我
遇见更好的自我 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:33

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

提交回复
热议问题