Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I update MongoDB document fields only if they don't exist?

Tags:

mongodb

I have collection foo with documents like:

{site_id: 'xxx', title: {ru: 'a', en: 'b'}, content: {ru: 'a', en: 'b'}} {site_id: 'xxx', title: {ru: 'c', de: 'd'}, content: {ru: 'c', de: 'd'}} 

I need to update multiple fields which are can exists or not:

db.foo.update(     { site_id: 'xxx'},     { $set: {'title.de': '', 'content.de': ''}},     {multi: true} ) 

But I need something like $set which will not overwrite value if it exists.

like image 434
Miraage Avatar asked Jul 18 '14 12:07

Miraage


People also ask

Does MongoDB Update create if not exists?

You can use upsert i.e. whenever you insert a value and it already exist then update would be performed. If the value does not already exist then it would get inserted.

Which operation in MongoDB searches a collection for updating a document if it is not found then insert new document?

Or in other words, upsert is a combination of update and insert (update + insert = upsert). If the value of this option is set to true and the document or documents found that match the specified query, then the update operation will update the matched document or documents.


1 Answers

You can add a query to your update statement:

db.foo.update({'title.de': {$exists : false}}, {$set: {'title.de': ''}}) 

Update

For your modified question my solution looks like this - would that work for you? (If not, why?)

db.foo.update({site_id: 'xxx', 'title.de': {$exists : false}}, {$set: {'title.de': ''}, {multi: true}) db.foo.update({site_id: 'xxx', 'content.de': {$exists : false}}, {$set: {'content.de': ''}}, {multi: true}) 
like image 85
nutlike Avatar answered Oct 02 '22 00:10

nutlike