MongoDB upsert with empty update document

4.8k views Asked by At

I'm trying to figure out how to insert a document into a collection iff the document is not already present in that collection. If the document is already present, the statement should be a no-op.

The approach I'm taking it to use an upsert with an empty update document:

db.collection.update({ ...query... }, { }, { upsert: true })

But Mongo tells me that "Update documents cannot be empty". How can I accomplish this without needlessly updating the existing document? Thanks.

Edit: My query document looks like this:

{
    "Chromosome" : "4",
    "Position" : 60000,
    "Identifier" : "rs1345",
    "ReferenceAllele" : "N"
}
2

There are 2 answers

4
JohnnyHK On BEST ANSWER

You can do this by using $setOnInsert in your update object which will only apply in the case the upsert results in an insert:

var query = {
    "Chromosome" : "4",
    "Position" : 60000,
    "Identifier" : "rs1345",
    "ReferenceAllele" : "N"
};
db.collection.update(query, {$setOnInsert: query}, {upsert: true})
0
Florian Winter On

Create a unique index on the fields you use in the query, then use insert. If an identical document already exists, the insert will fail.

(You may want an index anyway to make this operation fast)