Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb upsert command in nodejs

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]);
  }
})
like image 217
Ajeet Avatar asked Jun 02 '17 05:06

Ajeet


People also ask

What is MongoDB Upsert?

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).

Is there an Upsert option in the MongoDB insert command?

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.

How do you update an object in MongoDB node JS?

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.

How do I update node js files?

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.


1 Answers

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.

like image 131
Dan Nagle Avatar answered Sep 18 '22 14:09

Dan Nagle