简体   繁体   中英

MongoDB: how to update n records based on ObjectID

I've created a Collection containing 1 million documents, and I'm trying to select 50000 of these records based on the ObjectID, and update one of the values (i'm working in Mongo shell, running on Ubuntu).

Is it possible to define a 50000 document range? It doesn't matter which documents are included in the 50000 range, I simply want to ringfence a definite number of records and run an update operation using the primary id so that I can measure the performance time.

The code I've tried to run doesn't work:

  use Assignment
  var _start = new Date()
  db.FlightsDate.update({$set:{Airtime: 8888}}).limit(50000).hint({_id:1});
  var _end = new Date();
  print("Time to Bulk Update AirTime key for 50000 documents… " + ((_end _start)/1000));

...i'm gathering that MongoDB needs me to include a query in the command to specify which docs are to be updated (I now understand from reading other posts that .limit won't constrain the number of records than an .update writes to).

Please can anyone advise a method that'll enable me to define the number of records to be updated?

Grateful for advice.

R, Jon

If you are simply looking for a "range" that covers 50,000 of the documents in the collection then your best approach is to query and find the "starting" and "ending" documents of your range first. Then apply that "range" specification to your update.

 var start_id = db.FlightsDate.find({}).limit(1).toArray()[0]._id;
 var end_id = db.FlightsDate.find({}).skip(49999).limit(1).toArray()[0]._id;

 var _start = new Date();
 db.FlightsDate.update(
     { "_id": { "$gte": start_id, "$lte": end_id } },
     { "$set"; { "Airtime": 8888 } },
     { "multi": true }
 );

 var _end = new Date();
 ( _end - _start )/1000;

If you then wanted the next 50,000 in an additional range then :

 var start_id = db.FlightsDate.find(
     { "_id": { "$gt": end_id } }
 ).limit(1).toArray()[0]._id;

 var end_id = db.FlightsDate.find(
     { "_id": { "$gt": end_id } }
 ).skip(49999).limit(1).toArray()[0]._id;

And do it all again.

The point is you need to know where to "start" and when to "end" within a range to limit your update to just 50,000 documents without any other criteria to do so.

Also note the usage of "multi" in the update method there. By default, .update() does not "update" any more than one document, essentially being the first match. So what you mean to do is update "all documents in the range" and that is why you need to apply "multi" here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM