0
{
"_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?

Towhid
  • 1,920
  • 3
  • 36
  • 57

2 Answers2

5

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

Sydney
  • 11,964
  • 19
  • 90
  • 142
  • You can do also `db.bazars.update({"_id" : "O6"},{$set:{"bazar.2.value":5}})` if you know the index array – Barno Jul 23 '14 at 20:18
  • 1
    db.bazars.update({'id': 06}, {$set: {'bazar.kolaBazar.value':NumberInt(5)}}) is working for me. So could you please update your answer so I can accept it? And thanks for your nice suggestion. – Towhid Jul 23 '14 at 20:24
0

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

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

Eugene Kostrikov
  • 6,799
  • 6
  • 23
  • 25
  • I don't want to set `kolaBazar` to 5 but the **value** field of `kolaBazar` to 5 – Towhid Jul 23 '14 at 20:12
  • 1
    Oh, sorry. Then it's {$set: {'bazar.kolaBazar.value' : 5}} Just separate nested properties with dots and it doesn't matter how deeply it's nested. – Eugene Kostrikov Jul 23 '14 at 20:15