Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB: insert on duplicate key update

How can do this with Mongo in one [atomic] statement:

insert mytable set MyUniqueKey = ?, X = ? on duplicate key update Y = ?

When this statement is executed for first time it will set X value but after that it will only update Y value.

Only MyUniqueKey is part of unique key and should be looked up for duplicates.

like image 549
Ali Shakiba Avatar asked Apr 08 '12 01:04

Ali Shakiba


People also ask

How do I fix a duplicate key collection?

If there is more than one document without a value for the indexed field or is missing the indexed field, the index build will fail with a duplicate key error. You can combine the unique constraint with the sparse index to filter these null values from the unique index and avoid the error.

How do I update two values in MongoDB?

Update Multiple Fields of a Single Document. We can use $set and $inc operators to update any field in MongoDB. The $set operator will set the newly specified value while the $inc operator will increase the value by a specified value.

How do you stop insertion of duplicate documents in a MongoDB collection?

To insert records in MongoDB and avoid duplicates, use “unique:true”.


2 Answers

You are looking for the upsert option on the Update command. The docs should be enough here.

like image 85
Gates VP Avatar answered Sep 19 '22 10:09

Gates VP


I asked this question on mongodb user group, the answer was that it is not possible and this is an open issue.

like image 41
Ali Shakiba Avatar answered Sep 20 '22 10:09

Ali Shakiba