Reputation: 2585
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.
Upvotes: 17
Views: 30167
Reputation: 12904
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
Upvotes: 34