1

How can I push new key and value in JSON array?

I tried I used push keyword in update query but I got a different output. I used:

 db.users.updateOne({"name":"viki"},{$push{"address.district":"thambaram"}})

I have this document:

{ "_id" : ObjectId("58934f10c7592b1494fd9a4d"), "name" : "viki", "age" : 100, "subject" : [ "c", "node.js", "java" ], "address" : { "city" : "chennai", "state" : "tamilnadu", "pincode" : "123" } }

I want to add "district":"thambaram" in address json array

I need like:

{ "_id" : ObjectId("58934f10c7592b1494fd9a4d"), "name" : "viki", "age" : 100, "subject" : [ "c", "node.js", "java" ], "address" : { "city" : "chennai", "state" : "tamilnadu", "pincode" : "123","district":"thambaram"} }
9
  • What is the error you are getting Commented May 4, 2017 at 14:32
  • You can not use $push operator because this is not an array. You can use simple nested object property assignment. Commented May 4, 2017 at 14:34
  • i got this output: { "_id" : ObjectId("58934f10c7592b1494fd9a4d"), "name" : "viki", "age" : 100, "subject" : [ "c", "node.js", "java" ], "address" : { "city" : "chennai", "state" : "tamilnadu", "pincode" : "123", "district" : [ "thambaram" ] } } but I need { "_id" : ObjectId("58934f10c7592b1494fd9a4d"), "name" : "viki", "age" : 100, "subject" : [ "c", "node.js", "java" ], "address" : { "city" : "chennai", "state" : "tamilnadu", "pincode" : "123","district":"thambaram"} } Commented May 4, 2017 at 14:36
  • can you give me a code Commented May 4, 2017 at 14:39
  • 1
    Kindly accept my answer if it helped you. And we need to use push to add a new element to array. Your's was not an array. Commented May 4, 2017 at 17:32

1 Answer 1

1

Use $set

db.users.updateOne({"name":"viki"},{$set:{"address.district":"thambaram"}})

This should work.

The $push operator appends a specified value to an array. In your case you should use $set

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.