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?
collection. update() method updates a single document. Include the option multi: true to update all documents that match the query criteria.
db. collection. insertMany() can insert multiple documents into a collection.
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()}}) })
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With