st78
st78

Reputation: 8316

FindAndUpdate first 5 documents

I am looking to a way to FindAndModify not more than 5 documents in MongoDB.

This is collection for queue which will be processed from multiple workers, so I want to put it into single query.

While I cannot control amount of updates in UpdateOptions parameter, is it possible to limit number of rows which will be found in filterDefinition?

Upvotes: 1

Views: 1784

Answers (1)

B. Fleming
B. Fleming

Reputation: 7230

Problem 1: findAndModify() can only update a single document at a time, as per the documentation. This is an inherent limit in MongoDB's implementation.

Problem 2: There is no way to update a specific number of arbitrary documents with a simple update() query of any kind. You can update one or all depending on the boolean value of your multi option, but that's it.

If you want to update up to 5 documents at a time, you're going to have to retrieve these documents first then update them, or update them individually in a foreach() call. Either way, you'll either be using something like:

db.collection.update(
    {_id: {$in: [ doc1._id, doc2._id, ... ]}},
    { ... },
    {multi: true}
);

Or you'll be using something like:

db.collection.find({ ... }).limit(5).forEach(function(doc) {
    //do something to doc
    db.collection.update({_id: doc._id}, doc);
});

Whichever approach you choose to take, it's going to be a workaround. Again, this is an inherent limitation.

Upvotes: 3

Related Questions