Darshan theerth
Darshan theerth

Reputation: 536

How to update a document in MongoDB without inserting duplicate entry?

I have these docs in my collection.

{"_id": 1, "name": "Banana, "quantity": 3}
{"_id": 2, "name": "Apple, "quantity": 4}
{"_id": 3, "name": "Orange, "quantity": 5}

Now I need to edit the 2nd doc in the collection.

var doc = {"_id": 2}
var updateQuery = {"_id": 2, "name": "Banana", "quantity": 4}
var dataModified = { $set: updateQuery };

and use the updateOne query,

db.collection.updateOne(doc, dataModified) 

This works fine. But this will add the duplicate entry of "Banana" in the docs. Like this:

{"_id": 1, "name": "Banana, "quantity": 3}
{"_id": 2, "name": "Banana, "quantity": 4}
{"_id": 3, "name": "Orange, "quantity": 5}

So is there anyway, I could find out/restrict the duplicate entry of "name" field while updating the document?

Upvotes: 1

Views: 41

Answers (1)

mickl
mickl

Reputation: 49945

You can create unique index on name field and you'll get an exception when you try to insert duplicated value:

db.members.createIndex( { "name": 1 }, { unique: true } )

Upvotes: 2

Related Questions