user1027503
user1027503

Reputation:

Mongodb - update partial number of documents

it is possible in Mongodb to limit the number of documents that can be updated in one shot?

I have a list of item order by insertion date (ie. by _id), I just want to update the (example) 5 oldest one.

I can retrieve the inform I want

db.mycoll.find({}).limit(5)

I can update one (and therefore cycle on the results of the previous query) or all (or using a combination)

db.mycoll.update({"_id" : ObjectId("4f672a5175fa1c01c100001d")}, {$set: {'b' : 'test'}}, false, true)
db.mycoll.update({}, {$set: {'b' : 'test'}}, false, true)

But I could not pass a criteria with a limit on the update request. Any way to do it?

Upvotes: 4

Views: 6084

Answers (2)

cescgie
cescgie

Reputation: 151

You can do something like this

First get all records you want to update

var mycolls = db.mycoll.find({}).limit(5)

Then, map ids of these records

var mycollIDs = mycolls.map(x=>x._id)

Update all of these records using updateMany

db.mycolls.updateMany({_id:{$in:mycollIDs}},{set:{UPDATE DATA}})

Hope this could help!

Upvotes: 1

italkboy
italkboy

Reputation: 64

Unfortunately, you can look this: how-to-limit-number-of-updating-documents-in-mongodb

Unfortunately the workaround you have is the only way to do it AFAIK. There is a boolean flag multi which will either update all the matches (when true) or update the 1st match (when false).

Upvotes: 3

Related Questions