MongoDB upsert with empty update document

I am trying to figure out how to insert a document into a collection if the document is not already present in that collection. If the document is already present, the operator must be non-op.

The approach I am using to use upsert with an empty update document is:

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

      

But Mongo tells me that "Updating documents cannot be empty." How can I do this without unnecessarily updating an existing document? Thank.

Edit: my request document looks like this:

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

      

+3


source to share


2 answers


You can do this by using an $setOnInsert

in the update object, which will only be applied if the result of the upsert is inserted:



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

      

+4


source


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



(Anyway, you can get the index to quickly do this operation)

0


source







All Articles