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:
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
});