Skip to content

Latest commit

 

History

History
31 lines (23 loc) · 969 Bytes

mongo_upsert.md

File metadata and controls

31 lines (23 loc) · 969 Bytes

MongoDB: Insert, if not exists, a.k.a. upsert

MongoDB supports upsert operations, i.e. it would create a new document, if lookup does not return results, or it would update existing one.

There are 2 ways to achieve the same result:

  1. findOneAndUpdate with upsert option .
  2. findAndModify with upsert option .

Both operations must be executed with upsert and $setOnInsert.

db.people.findOneAndUpdate(
    { id: "$(account-id)-$(idempotency-key)" },
    { $setOnInsert: { status: "in-flight" }},
    { upsert: true, returnNewDocument: false }
);
  
# or

db.people.findAndModify({
    query: { id: "$(account-id)-$(idempotency-key)" },
    update: { $setOnInsert: { status: "in-flight" }},
    upsert: true,
    new: false
});