Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb only insert if value is unique, else update - in node.js

I've started developing an app recently and have finally got my node.js server communicating with my mongodb database.

I want to insert a bunch a JSON objects that look something like this:

   {
    'Username': 'Bob',
    'longitude': '58.3',
    'latitude': '0.3'
   }

If this Object is inserted into myCollection, and then I try to insert an object again with the Username Bob, but with different coordinates, I want the latest 'Username': 'Bob' object to replace the earlier one. There can only be one object in myCollection with the 'Username': 'Bob' basically.

If this was a relational database I would make Bob a primary key or something, but I was wondering what the best way to do this with mongoDb would be. Should I use the update+upsert method? I tried that and it didn't seem to work!

Apologies if this seems like a silly question, but I am still new to all of this.

like image 409
DeaIss Avatar asked Apr 03 '14 21:04

DeaIss


People also ask

Does MongoDB update insert if not exists?

You can use upsert i.e. whenever you insert a value and it already exist then update would be performed. If the value does not already exist then it would get inserted.

How do you ensure a field is unique in MongoDB?

To create a unique index, use the db. collection. createIndex() method with the unique option set to true .

How do you update if exists otherwise insert new document?

In order to create a document if it doesn't already exist, you need to pass { upsert : true } in the options hash as it defaults to false . i.e. update is deprecated. Use updateOne, updateMany, or bulkWrite instead.

Is there an Upsert option in the MongoDB insert command?

Since upsert is defined as operation that "creates a new document when no document matches the query criteria" there is no place for upserts in insert command.


1 Answers

Yes, a simple update query with the upsert option should satisfy your use case:

db.collection.update(
   {username:"Bob"},
   {$set:{'longitude': '58.3', 'latitude': '0.3'}},
   { upsert: true}
)

When you run the above query the first time (i.e., Bob doesn't exist in the collection), a new document is created. But when you run it the second time with new values for lat/long, the existing document is updated with the new lat/long values.

You can also create a unique index on the username field to prevent multiple records for 'Bob' from being created even accidentally:

db.collection.ensureIndex( { "username": 1 }, { unique: true } )

EDIT:

db.collection.ensureIndex() is now deprecated and is an alias for db.collection.createIndex(). So, use db.collection.createIndex() for creating indexes

like image 109
Anand Jayabalan Avatar answered Oct 13 '22 19:10

Anand Jayabalan