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 to share