Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update a collection in mongodb

Tags:

mongodb

I had a json which is inserted in my mongo collection.Now I want to update the same json that is inserted in the collection,in such a way that I need to add new data element to that collection using the id which will be generated earlier. eg:

{
 "name":"sam",
 "age":20,
  "_id":""5sq8uye1236g'
 }

If above is the json what is inserted in one collection where we have _id generated for it in collection. Now I had variable called token .

var token=12345

Now I want to update the above collection such that this token gets added to it based on the _id of that. Required format in collection:

{
"name":"sam",
"age":20,
 "token":12345,
"_id":""5sq8uye1236g'
 } 

How can I do that?

like image 711
H Varma Avatar asked Oct 31 '25 23:10

H Varma


1 Answers

Use update command.

Your query should look like

db.collection.update({_id:'5sq8uye1236g'},{$set :{token :12345});

Read more about updating here

like image 137
Ankit Avatar answered Nov 03 '25 13:11

Ankit