0

Is there a way to omit adding/updating document if it was found in the collection without doing two requests to Mongo server? It would be perfect if this can be done in bulk, but I would appreciate to hear other options or workarounds.

What I'm looking for is sort of opposite of upsert option:

var bulk = MyCollection.initializeUnorderedBulkOp();
bulk.find({ x: val }).upsertOnlyIfNotFound({ x: newVal });
bulk.execute();

1 Answers1

3

What you are looking for is $setOnInsert.

db.MyCollection.update(
  { x: val },
  {
     $setOnInsert: { x: "newVal" }
  },
  { upsert: true }
)

From the documentation :

If an update operation with upsert: true results in an insert of a document, then $setOnInsert assigns the specified values to the fields in the document. If the update operation does not result in an insert, $setOnInsert does nothing.

HIRA THAKUR
  • 17,189
  • 14
  • 56
  • 87