Updating a document field in mongo based on a different field value

Suppose I have two fields F1 and F2. I want to update F1 to become F1 + ", " + F2 . Can I do this with a single update command in mongo?

+6
source share
2 answers

No, you cannot do this. You cannot use expressions in mongodb updates. The only way is to get this document to the client, compose a new field value and release the prepared update statement.

+4
source

As mentioned by Sergio, you cannot do this even a year after the question was asked with version 2.4.8 . But if you need to do this, you can use this

 db.yourCollection.find({}).forEach(function(doc) { doc.F1 = doc.F1 + ", " + doc.F2; delete doc.F2; db.yourCollection.save(doc); }); 
+2
source

Source: https://habr.com/ru/post/913619/


All Articles