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