mongodb

How to update all documents with a field equal to the length of another field in Mongo


I know I can do something like this to update the field to a specific value:

db.coll.update({},{ $set: {'fieldName': 'fieldValue' } }, { multi:true });

However, I need to update the value of a field equal to the number of values in an array field of the same document. I know this probably requires aggregate function but am newer to Mongo and could use some help constructing the query. It also needs to be done for every document in the collection.


Solution

  • The query that ended up working for me:

    var bulkOp = db.posts.initializeUnorderedBulkOp(); 
    var count = 0;
    
    db.posts.aggregate([
        { "$match": { 
            "_likes": { "$exists": true }
        }}, 
        { "$project": { "likeCount": { "$size": "$_likes" } } }
    ]).forEach(function(doc) { 
            bulkOp.find({ "_id": doc._id }).updateOne({ 
                "$set": { "likeCount": NumberInt(doc.likeCount) }
            });
            count++;
            if (count % 200 === 0) {
                // Execute per 200 operations and re-init
                bulkOp.execute();
                bulkOp = db.posts.initializeUnorderedBulkOp();
            }
    })
    
    // Clean up queues
    if (count > 0) { 
        bulkOp.execute();
    }