0

I have a users collection with a likes array. I need to update all of the likes for every user.

I wrote a script to do that, but it is crazy slow. I need to update tens of millions of users.

db.users.find().forEach( function(user) {   
  users.likes.forEach( function(like){ 
    like.stars = 5;
  });

  db.users.save(user);
});

Do you know any faster way to achieve this?

EDIT:

A sample document would look like:

{
  "_id" : ObjectId("4f0f31ab0c20020600012301"),
  "created_at" : ISODate("2012-01-12T19:16:59.748Z"),
  "predictions" : null,
  "likes" : [ 
    {
      "_id" : ObjectId("4f0f4a3978c7890600020f2b"),
      "brand_id" : "bcbgmaxazria"
    }
  ],
  "updated_at" : ISODate("2012-12-19T10:09:20.000Z")
}

I want to add a new stars field with the value 5 to all of the objects in the likes collections.

  • 1
    Can you please show a sample document? And if I get that straight, each of the likes array entries holds a document in which one field is named `stars`? And what you would like to do is to set all occurrences of stars to 5? – Markus W Mahlberg Nov 17 '14 at 15:00

1 Answers1

0

There is a general problem with that. Please see https://stackoverflow.com/a/4669702/1296707 for details - and don't forget the kudos! ;)

However, you might get it done a bit faster using bulk operations.

var bulk = db.users.initializeUnorderedBulkOp()

db.users.find().forEach(
  function(user){
    user.likes.forEach(
      function(like){ like.stars = 5; }
    );
  bulk.find({_id:user._id}).replaceOne(user)
 });

 bulk.execute();

This is in the mongo shell and should work. It should be faster, too.

Community
  • 1
  • 1
Markus W Mahlberg
  • 19,711
  • 6
  • 65
  • 89