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.
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.
To create a unique index, use the db. collection. createIndex() method with the unique option set to true .
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.
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.
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
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