Ali Shakiba
Ali Shakiba

Reputation: 21277

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.

Upvotes: 16

Views: 26425

Answers (3)

Mattis Asp
Mattis Asp

Reputation: 1003

From

$setOnInsert

I would call it "MyCollection" instead of "mytable". You can do the following:

db.mycollection.update(
   { MyUniqueKey: "?" },
   {  
      $set: {"y": "?"},
      $setOnInsert: {
          MyUniqueKey: "?",
           "x": "?",
   },
   { upsert: true }
)

Basically the $set runs always, except when document does not exist. Then $setOnInsert will run.

Upvotes: 5

Gates VP
Gates VP

Reputation: 45307

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

Upvotes: 16

Ali Shakiba
Ali Shakiba

Reputation: 21277

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

Upvotes: 5

Related Questions