i have this collection (not exactly what I have, just for example). I want to update all "numberOfViewsPerWeek" field into 0 just like reset.
{
"_id" : ObjectId("594d2359bf170b0828690bf7"),
"owner" : ObjectId("594c126285f0922a985083c1"),
"numberOfViewsSincePost" : 15,
"numberOfViewsPerWeek" : 4,
}
{
"_id" : ObjectId("594d709addb8691cf067fa73"),
"owner" : ObjectId("594c126285f0922a985083c1"),
"numberOfViewsSincePost" : 10,
"numberOfViewsPerWeek" : 2,
}
{
"_id" : ObjectId("764d709addb8691cf067fa70"),
"owner" : ObjectId("594c126285f0922a985083c1"),
"numberOfViewsSincePost" : 12,
"numberOfViewsPerWeek" : 7,
}
...
I'd try to use update but it only update the first document, my code is this
Property.update({}, {'$set': {'numberOfViewsPerWeek' : 0}}, function(error, properties){
if(error){
console.log(error);
}
if(!properties){
console.log('Something went wrong');
}
console.log('success update view');
});
what should I do? thanks in advance
I actually think a lot of people have problems with this.
You should include an option called multi: true
.
Ex:
Property.update({}, {'$set': {'numberOfViewsPerWeek' : 0}}, {multi: true},
function(error, properties){/* ... rest of the code*/
Docs:
By default, the update() method updates a single document. Set the Multi Parameter to update all documents that match the query criteria.
I don't know why they did this, I find it unintuitive.
In my opinion updating all documents should be the default.
Update for mongo >= 3.2: To resolve the confusion prefer using .updateOne
or .updateMany
which sets the multi
flag automatically.
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