Reputation: 85056
I have a collection where I would like to update a date in every record with a random time in the last few hours. I have been using the update below:
db.users.update(
{},
{
$set:
{
loggedIn: new Date((ISODate().getTime() - 1000*60*(ISODate().getTime()%300)))
}
},
false,
true
);
But this updates every record with the same random time. How can I get the 1000*60*(ISODate().getTime()%300
portion to execute with every update instead of executing once and then updating the records with the same value?
Upvotes: 0
Views: 569
Reputation: 151122
That's right. The operation is atomic and the "random date value" here is being evaluated once, then applied to all records with your multi
update.
So in whatever programming implementation you want the iterative form:
db.users.find({}).foreach(function(user) {
db.users.update({ _id: user._id },
{
$set:
{
loggedIn: new Date((ISODate().getTime() - 1000*60*(ISODate().getTime()%300)))
}
});
};
There is work on batch updates, but even so you would need to generate your "random time" for each document
Upvotes: 3