Search code examples
mongodbmongo-shell

How to update document inside a document in MongoDB?


{
"_id" : O5,
"bazar" : {
    "indiraBazar" : {
        "units" : "taka",
        "no" : 560,
        "value" : 0.90
    },
    "dhakaBazar" : {
        "no" : "no item",
        "value" : 1
    },
    "kolaBazar" : {
        "no" : "unlimited",
        "value" : 4
    }
},
"vat" : false,
"total" : 2

}

Say above document is under bazars collection. Here how will I set value filed of kolaBazar to 5 from 4?


Solution

  • The query would update as requested: db.bazars.update({'bazar.kolaBazar.value': 4}, {$set: {'bazar.kolaBazar.value':NumberInt(5)}}).

    EDIT: That query also works: db.bazars.update({'id': 06}, {$set: {'bazar.kolaBazar.value':NumberInt(5)}})

    But I would change the schema to ease your query.

    {
        "_id" : "O6",
        "bazar" : [ 
            {
                "_id" : "indiraBazar",
                "units" : "taka",
                "no" : 560,
                "value" : 0.9
            }, 
            {
                "_id" : "dhakaBazar",
                "no" : "no item",
                "value" : 1
            }, 
            {
                "_id" : "kolaBazar",
                "no" : "unlimited",
                "value" : 4
            }
        ],
        "vat" : false,
        "total" : 2
    }
    

    The new query would be db.bazars.update({'bazar._id':'kolaBazar'}, {$set:{'bazar.$.value':NumberInt(5)}})