Reputation: 6502
Let's assume I have 10000k of users I want to select first 500 users and set golden status for them
Is it possible to do that with mongo batch (bulk) opertions?
Upvotes: 1
Views: 69
Reputation: 3734
You can change multiple documents in tn mongoDB using update
. But the query can't use $limit
or $orderby
. Check this issue. So you will need to write a query(as in find) and update documents. If your schema has the ranking of the users, it is very trivial to do that.
db.users.update({rank:{'$lte':500}},{'$set':{status:'gold'}})
But if you have a score based on which you will rank them, it is not so trivial. There is no batch operation. You will need to have to do it yourself for ex. using forEach()
db.users.find({}).sort({score:-1}).limit(500).forEach(...)
in the forEach you can manually set the golden status.
A shrewd way to avoid this is make a query to know the score of the 500th ranked user and use that to update.
db.users.find({}).sort({score:-1}).skip(499).limit(1)
or
db.users.find({}).sort({score:-1}).skip(500)
I don't how it is done in pymongo. Let us assume that docs
is the query output.
fooScore=docs[0].score
or
fooScore=docs[500].score
and
db.users.update({score:{'$gte':{fooScore}},{'$set':{status:'gold'}})
Also you will have to deal differently when users are less than 500.
Tinker the strategy for users with same score...
Also consider setting an index
on rank or score for efficient queries.
Upvotes: 2