Contents of page >
Update documents (records) in collection (table) in mongoDB >
1) Before updating let’s create and query collection in MongoDB
Let's create collection and insert documents in it before update >
> db.employee.insert({id : 1, firstName:"ankit"})
> db.employee.insert({id : 2, firstName:"sam"})
|
First line above will create table (or collection) (if table already exists it will insert documents in it).
Let's query/see what is there in collection before update >
> db.employee.find();
{ "_id" : ObjectId("584ebed11127dea5ece72742"), "id" : 1, "firstName" : "ankit" }
{ "_id" : ObjectId("584ebee21127dea5ece72743"), "id" : 2, "firstName" : "sam" }
|
2) UPDATE Example1 in MongoDB >
Let’s UPDATE firstname where id=1 >
We will use update method of mongoDB
> db.employee.update({id:1},{$set:{firstName:"ankit_UPDATED"}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
|
Let’s understand meaning of statement
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
"nMatched" : 1 shows that there was 1 result found corresponding to id=1 and
"nModified" : 1 shows that there was 1 document modified.
Now let's display documents of collection after update >
> db.employee.find();
{ "_id" : ObjectId("584ebed11127dea5ece72742"), "id" : 1, "firstName" : "ankit_UPDATED" }
{ "_id" : ObjectId("584ebee21127dea5ece72743"), "id" : 2, "firstName" : "sam" }
|
3) UPDATE Example2 in MongoDB >
Let’s UPDATE id where firstName= "sam" >
> db.employee.update({firstName:"sam"},{$set:{id:22}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : "sam" })
|
Now, let's display documents of collection after update >
> db.employee.find();
{ "_id" : ObjectId("584ebed11127dea5ece72742"), "id" : 1, "firstName" : "ankit_UPDATED" }
{ "_id" : ObjectId("584ebee21127dea5ece72743"), "id" : 22, "firstName" : "sam" }
|
4) SUMMARY>
So in this mongoDB tutorial we learned how to Update documents in collection in mongoDB.
UPDATE Example1 in MongoDB >
Let’s UPDATE firstname where id=1 >
> db.employee.update({id:1},{$set:{firstName:"ankit_UPDATED"}})
|
UPDATE Example2 in MongoDB >
Let’s UPDATE id where firstName= "sam" >
> db.employee.update({firstName:"sam"},{$set:{id:22}})
|
Having any doubt? or you liked the tutorial! Please comment in below section.
Please express your love by liking JavaMadeSoEasy.com (JMSE) on facebook, following on google+ or Twitter.
RELATED LINKS>
What is MongoDB - A quick introduction to database
objectId in MongoDB
Create new database in mongoDB
Create new collection(table) in mongoDB
Data Modelling in MongoDB - Multiple tables
Delete documents in collection (table) in mongoDB
Labels:
MongoDB