Update all documents in a collection with random numbers
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 thebody
function is written. Onlyjs
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.