6

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]);
  }
})
3
  • 1
    What have you tried? There are many examples of upsert operations in the core documentation and on this very site. What is it you do not understand about how to do this?
    – Neil Lunn
    Commented Jun 2, 2017 at 5:10
  • I browsed this. First, i understood that I should have a set if the already existing record (source). then upcoming records(target). But not sure where I should use a query like a thing that I only want to insert and update on the basis of my id field. collection.update( source, target, { upsert: true }, function(err, result, upserted) { ... });
    – Ajeet
    Commented Jun 2, 2017 at 5:18
  • Yes that as a call signature of the method, but not necessarily representative of your actual code. How are you actually using it in context? What is the error/problem? Please use the Edit link on your question to add details rather than posting comments.
    – Neil Lunn
    Commented Jun 2, 2017 at 5:21

1 Answer 1

15

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.