I have a collected named foo
hypothetically.
Each instance of foo
has a field called lastLookedAt which is a UNIX timestamp since epoch. I'd like to be able to go through the MongoDB client and set that timestamp for all existing documents (about 20,000 of them) to the current timestamp.
What's the best way of handling this?
To update a single field or specific fields just use the $set operator. This will update a specific field of "citiName" by value "Jakarta Pusat" that defined by $set operator.
Mongoose | updateMany() Function The updateMany() function is same as update(), except MongoDB will update all documents that match the filter. It is used when the user wants to update all documents according to the condition.
To update multiple documents in a collection, set the multi option to true. multi is optional. If set to true, updates multiple documents that meet the query criteria. If set to false, updates one document.
Regardless of the version, for your example, the <update>
is:
{ $set: { lastLookedAt: Date.now() / 1000 } }
However, depending on your version of MongoDB, the query will look different. Regardless of version, the key is that the empty condition {}
will match any document. In the Mongo shell, or with any MongoDB client:
$version >= 3.2:
db.foo.updateMany( {}, <update> )
{}
is the condition (the empty condition matches any document)3.2 > $version >= 2.2:
db.foo.update( {}, <update>, { multi: true } )
{}
is the condition (the empty condition matches any document){multi: true}
is the "update multiple documents" option$version < 2.2:
db.foo.update( {}, <update>, false, true )
{}
is the condition (the empty condition matches any document)false
is for the "upsert" parametertrue
is for the "multi" parameter (update multiple records)This code will be helpful for you
Model.update({
'type': "newuser"
}, {
$set: {
email: "[email protected]",
phoneNumber:"0123456789"
}
}, {
multi: true
},
function(err, result) {
console.log(result);
console.log(err);
})
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