How to implement somethings similar to db.collection.find().limit(10)
but while updating documents?
Now I'm using something really crappy like getting documents with db.collection.find().limit()
and then updating them.
In general I wanna to return given number of records and change one field in each of them.
Thanks.
The Limit() Method To limit the records in MongoDB, you need to use limit() method. The method accepts one number type argument, which is the number of documents that you want to be displayed.
9. The __________ method limits the number of documents in the result set. Explanation: limit() corresponds to the LIMIT statement in SQL.
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} );
Using forEach
to individually update each document is slow. You can update the documents in bulk using
ids = db.collection.find(<condition>).limit(<limit>).map( function(doc) { return doc._id; } ); db.collection.updateMany({_id: {$in: ids}}, <update>})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With