Reputation: 1257
I have some documents in my MongoDB collection, they look like this:
number: first
value: 1
number: two
value: 2
number: three
value: 3
I want to update all the documents in the collection so that the value
field of each document is changed to a random number, like this:
number: first
value: 4747
number: two
value: 1024
number: three
value: 102
I tried the following code:
cursor = db.mycol.find()
for record in cursor:
record = db.mycol.raplace_many({}, {"value": random.randrange(10000)})
The problem with this is that instead of updating each document with a new random value, it updates all of them with the same random value, like this:
number: first
value: 1024
number: two
value: 1024
number: three
value: 1024
Why is this happening? I tried the same thing, but with update_many
instead of replace, but the output is the same. Every advice is appreciated!
On the other hand, if i try to insert the value using insert_one
the output will be the expected, so each field will have a different random value.
Upvotes: 0
Views: 74
Reputation: 3010
The following code can do the trick:
//Fetching the array of object IDs from the collection.
var objectIDs= db.collection.distinct("_id");
// Iterating over the array and updating the 'value' correspond to each object ID with a random value. Since there is a default index on object ID, the operation would be fast.
objectIDs.forEach(id=>{
db.collection.update(
{
"_id":id
},
{
$set:{
"value": Math.floor(Math.random() * 10000)
}
}
)
});
Before update:
{ "_id" : ObjectId("5d8774e19f062d4c422b3ab4"), "value" : 1 }
{ "_id" : ObjectId("5d8774e19f062d4c422b3ab5"), "value" : 1 }
{ "_id" : ObjectId("5d8774e19f062d4c422b3ab6"), "value" : 1 }
{ "_id" : ObjectId("5d8774e19f062d4c422b3ab7"), "value" : 1 }
{ "_id" : ObjectId("5d8774e19f062d4c422b3ab8"), "value" : 1 }
{ "_id" : ObjectId("5d8774e19f062d4c422b3ab9"), "value" : 1 }
{ "_id" : ObjectId("5d8774e19f062d4c422b3aba"), "value" : 1 }
{ "_id" : ObjectId("5d8774e19f062d4c422b3abb"), "value" : 1 }
{ "_id" : ObjectId("5d8774e19f062d4c422b3abc"), "value" : 1 }
{ "_id" : ObjectId("5d8774e19f062d4c422b3abd"), "value" : 1 }
After update:
{ "_id" : ObjectId("5d8774e19f062d4c422b3ab4"), "value" : 3538 }
{ "_id" : ObjectId("5d8774e19f062d4c422b3ab5"), "value" : 9678 }
{ "_id" : ObjectId("5d8774e19f062d4c422b3ab6"), "value" : 8325 }
{ "_id" : ObjectId("5d8774e19f062d4c422b3ab7"), "value" : 2986 }
{ "_id" : ObjectId("5d8774e19f062d4c422b3ab8"), "value" : 6159 }
{ "_id" : ObjectId("5d8774e19f062d4c422b3ab9"), "value" : 4564 }
{ "_id" : ObjectId("5d8774e19f062d4c422b3aba"), "value" : 7185 }
{ "_id" : ObjectId("5d8774e19f062d4c422b3abb"), "value" : 2585 }
{ "_id" : ObjectId("5d8774e19f062d4c422b3abc"), "value" : 7073 }
{ "_id" : ObjectId("5d8774e19f062d4c422b3abd"), "value" : 4094 }
Upvotes: 1