15 Jun 2014
mongoDB – Update a document in database
As in SQL We use update command for updating a record, We do the same in No SQL databases. DB. We use update command. This approach is known as wholesale update of a document.
Suppose we have a document in users collection.
> { _id :1, "name": "Mike"}
Following is Syntax of update.
- > db.collection.update(query, update, options)
Query is like where clause in SQL, it will specify which document to select. and second array will be the values to update. This will replace every field in document with the update value except _id field.
> db.users.update({"name":"Mike" }, {"name": "Thompson", "salary": 5000});
This query will update document where name =”Mike” with name= “Thompson” and salary = 5000. Document will be in this form
> { _id :1, "name": "Thompson", "salary": 5000}
Consider another example
> { "_id" : "Texas", "population" : 2500000, "land_locked" : 1 }
if we run this query
> db.foo.update({_id:"Texas"},{population:30000000})
Then document will become as
> { "_id" : "Texas", "population" : 30000000 }