Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB upsert with empty update document

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"
}
like image 420
Brian Berns Avatar asked Jun 10 '15 01:06

Brian Berns


1 Answers

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})
like image 189
JohnnyHK Avatar answered Sep 19 '22 00:09

JohnnyHK