Towhid
Towhid

Reputation: 2084

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?

Upvotes: 0

Views: 2284

Answers (2)

Sydney
Sydney

Reputation: 12212

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)}})

Upvotes: 5

Eugene Kostrikov
Eugene Kostrikov

Reputation: 7119

Just treat them as 'dot.separated.nested.properties'

So it would be {$set: {'bazar.kolaBazar': 5}} in your case

Upvotes: 0

Related Questions