-1

How to update data in mongodb?

This is my actual structure of my collection

db.collection.find().pretty()
{
    "_id" : ObjectId("557914833ac61e518e6103ab"),
    "dataValue" : {
        "value1" : [
            "value1 A",
            "value1 B"
        ]
    }
}

I want to insert like default in dataValue

db.collection.find().pretty()
{
    "_id" : ObjectId("557914833ac61e518e6103ab"),
    "dataValue" : {
        "value1" : [
            "value1 A",
            "value1 B"
        ],
        "default" : [
            "default A",
            "default B"
        ]
    }
}

Please help me

Community
  • 1
  • 1
Arav KT
  • 301
  • 6
  • 18
  • https://docs.mongodb.com/manual/reference/method/db.collection.update/ – Alex Jul 07 '17 at 12:43
  • 1
    Possible duplicate of [Add new field to a collection in MongoDB](https://stackoverflow.com/questions/7714216/add-new-field-to-a-collection-in-mongodb) – felix Jul 07 '17 at 12:49

2 Answers2

2

Try this:

db.collection.update(
   { _id: ObjectId("557914833ac61e518e6103ab") }, //update doc with this id
   { $set:
      {
        "dataValue.default": [
         "default A", 
         "default B" 
         ]
      }
   }
)

As per my comment: https://docs.mongodb.com/manual/reference/method/db.collection.update/

Syntax of update is (we're only using the <query> and <update> parts of this

db.collection.update(
   <query>,
   <update>,
   {
     upsert: <boolean>,
     multi: <boolean>,
     writeConcern: <document>,
     collation: <document>
   }
)

In your case, you need to use $set

dataValue.default uses dot notation to 'reach inside' the sub document, and set the property

Alex
  • 37,502
  • 51
  • 204
  • 332
0

This can be achived with a simple update with a $set operator

db.collection.update({"_id" : ObjectId("557914833ac61e518e6103ab")},
{ $set: {"dataValue.default" : [
            "default A",
            "default B"
        ]}})
Kevin Smith
  • 13,746
  • 4
  • 52
  • 77