How to limit number of updating documents in mongodb

You can use:

db.collection.find().limit(NUMBER_OF_ITEMS_YOU_WANT_TO_UPDATE).forEach(
    function (e) {
        e.fieldToChange = "blah";
        ....
        db.collection.save(e);
    }
);

(Credits for forEach code: MongoDB: Updating documents using data from the same document)

What this will do is only change the number of entries you specify. So if you want to add a field called “newField” with value 1 to only half of your entries inside “collection”, for example, you can put in

db.collection.find().limit(db.collection.count() / 2).forEach(
    function (e) {
        e.newField = 1;
        db.collection.save(e);
    }
);

If you then want to make the other half also have “newField” but with value 2, you can do an update with the condition that newField doesn’t exist:

db.collection.update( { newField : { $exists : false } }, { $set : { newField : 2 } }, {multi : true} );

Leave a Comment