I have created a collection named Account.
At first shot, I am inserting around 5 records.
{"Id":"0012800000C6Q19AAF","Name":"Aditya Kumar"}
{"Id":"0012800000C6MldAAF","Name":"GenePoint"}
{"Id":"0012800000C6MlbAAF","Name":"United Oil & Gas, UK"}
{"Id":"0012800000C6MlcAAF","Name":"United Oil & Gas, Singapore"}
{"Id":"0012800000C6MlTAAV","Name":"Edge Communications"}
{"Id":"0012800000C6MlUAAV","Name":"Burlington Textiles Corp of America"}
I am bringing data from the external system, which has already an ID field associated with it.
Again next time when a request comes for inserting extra 5 records, I want to check if Id field of upcoming records already exists in my MongoDB(if yes, then do an update else insert).
And don't get confused by Id field coming from external system with _Id field created for every MongoDB document.
Here is what I have tried:
var x= fields["data"]; obj='Account';
db.createCollection(obj);
db.collection(obj).insert(fields, function(err, doc) {
if (err) {
handleError(res, err.message, "Failed to create new contact.");
} else {
res.status(201).json(doc.ops[0]);
}
})
In MongoDB, upsert is an option that is used for update operation e.g. update(), findAndModify(), etc. Or in other words, upsert is a combination of update and insert (update + insert = upsert).
Here in MongoDB, the upsert option is a Boolean value. Suppose the value is true and the documents match the specified query filter. In that case, the applied update operation will update the documents. If the value is true and no documents match the condition, this option inserts a new document into the collection.
You can update a record, or document as it is called in MongoDB, by using the updateOne() method. The first parameter of the updateOne() method is a query object defining which document to update. Note: If the query finds more than one record, only the first occurrence is updated.
You can update a single document using the collection. updateOne() method. The updateOne() method accepts a filter document and an update document. If the query matches documents in the collection, the method applies the updates from the update document to fields and values of them.
Use the updateOne method:
db.collection.updateOne(
{ _id: id },
{ $set: { name: 'name' } },
{ upsert: true }
);
If a record with the matching id
is found then the name
field will be updated, otherwise a new record will be created.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With