Is it possible to update a mongo doc from inside a cursor traversal function (similar to mongoose)?
Something like:
db.collection.find({email:"[email protected]"}).forEach(doc => {
doc.newProp = 'newValue';
doc.save();
});
The MongoDB shell provides the following methods to update documents in a collection: To update a single document, use db. collection. updateOne()
MongoDB's update() and save() methods are used to update document into a collection. The update() method updates the values in the existing document while the save() method replaces the existing document with the document passed in save() method.
In MongoDB, the find() method return the cursor, now to access the document we need to iterate the cursor. In the mongo shell, if the cursor is not assigned to a var keyword then the mongo shell automatically iterates the cursor up to 20 documents. MongoDB also allows you to iterate cursor manually.
Try with below query, It should solve your issue:-
db.collection.find({email:"[email protected]"}).forEach(doc => {
db.collection.update({_id: doc._id},{$set:{"newProp":"value"}});
});
$set will update the existing value,Otherwise It will add new field with the given value if it not present in the document.
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