Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to limit number of updating documents in mongodb

Tags:

mongodb

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.

like image 365
awsum Avatar asked Jul 06 '11 02:07

awsum


People also ask

How do I limit documents in MongoDB?

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.

Which method limits the number of documents in the result set in MongoDB?

9. The __________ method limits the number of documents in the result set. Explanation: limit() corresponds to the LIMIT statement in SQL.


2 Answers

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} ); 
like image 172
Nick Avatar answered Sep 19 '22 11:09

Nick


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>}) 
like image 29
baylee Avatar answered Sep 17 '22 11:09

baylee