Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update all documents in a collection with random numbers

Tags:

I am trying to update all documents in a collection with random numbers.

Each document should have a different number.

My current code

db.myDoc.update(   { rand : { $exists : false } },   { $set : { rand: Math.random() } },   { multi : true } ) 

populates ALL documents with the SAME random value.

How to fix?

like image 722
checklist Avatar asked Nov 21 '14 15:11

checklist


People also ask

Which command is used to update all documents in a collection?

collection. update() method updates a single document. Include the option multi: true to update all documents that match the query criteria.

What function inserts multiple documents into a collection?

db. collection. insertMany() can insert multiple documents into a collection.


2 Answers

You can make use of the cursor.forEach() cursor method in the mongo shell to achieve this:

db.myDoc.find({rand: {$exists : false }}).forEach(function(mydoc) {   db.myDoc.update({_id: mydoc._id}, {$set: {rand: Math.random()}}) }) 
like image 199
Anand Jayabalan Avatar answered Sep 17 '22 15:09

Anand Jayabalan


Starting in Mongo 4.4, the $function aggregation operator allows applying a custom javascript function to implement behaviour not supported by the MongoDB Query Language.

For instance, in order to update documents with a random value:

// { "x" : 1 } // { "x" : 2 } db.collection.updateMany(   { rand: { $exists: false } },   [{ $set:     { rand:       { $function: {           body: function() { return Math.random(); },           args: [],           lang: "js"       }}     }   }] ) // { "x" : 1, "rand" : 0.7012578283384967  } // { "x" : 2, "rand" : 0.21041874709692365 } 

$function takes 3 parameters:

  • body, which is the function to apply.
  • args, which contains the fields from the record that the function can take as parameter. In our case we don't need any reference to the document itself in order to compute a random value, thus the empty array.
  • lang, which is the language in which the body function is written. Only js is currently available.

Note that this is now way more efficient than a find/foreach option since everything is done server side in one pass.

like image 40
Xavier Guihot Avatar answered Sep 17 '22 15:09

Xavier Guihot