Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I update a mongo document from inside a cursor traversal function?

Tags:

mongodb

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();
});
like image 685
Radu Luncasu Avatar asked Apr 02 '18 12:04

Radu Luncasu


People also ask

Can we update document in MongoDB?

The MongoDB shell provides the following methods to update documents in a collection: To update a single document, use db. collection. updateOne()

How do I update entries in MongoDB?

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.

How cursor can be used in MongoDB?

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.


1 Answers

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.

like image 189
gajju_15 Avatar answered Sep 28 '22 07:09

gajju_15