1
{
    "__v" : 2,
    "_id" : ObjectId("54dc4fd10ac1f6a066a0646c"),
    "desc" : "test1",
    "lists" : [ 
        {
            "index" : 1,
            "text" : "__point",
            "_id" : ObjectId("54dc4fda0ac1f6a066a0646d"),
            "createdAt" : ISODate("2015-02-12T07:01:46.390Z")
        }, 
        {
            "index" : 2,
            "text" : "__point",
            "_id" : ObjectId("54dc4fdd0ac1f6a066a0646e"),
            "createdAt" : ISODate("2015-02-12T07:01:49.668Z")
        }
    ],
    "name" : "test" }

The test array looks like this. i want to add 'category' field and add value '0' in lists checking _id.

i tried

$collection->update(array('_id' => new MongoId("54dc4fd10ac1f6a066a0646c")),array('$set' => array(new MongoId("54dc4fda0ac1f6a066a0646d").".lists.category" => '0')));

like this but it doesn't work.

Mark
  • 73
  • 1
  • 8
  • This might help you. http://stackoverflow.com/questions/5646798/mongodb-updating-subdocument Scott – m8a Feb 12 '15 at 10:09

2 Answers2

0

Hi I don't know more about PHP but you can do this from following script

    db.collectionName.find({
    "lists": {
    "$exists": true
    }
}).forEach(function(data){
    for(vari=0;i<data.lists.length;i++){
    db.collectionName.update({
        "_id": data._id,
        "lists.index": data.lists[
            i
        ].index
    },
    {
        "$set": {
            "lists.$.category": 0
        }
    },
    true,
    true);
    }
})
Neo-coder
  • 7,715
  • 4
  • 33
  • 52
0
set third parameter of update to true.
i think there is some problem in finding which embedded document for updated.
try this one might be work.
$collection->update(array('_id' => new MongoId("54dc4fd10ac1f6a066a0646c"), 'lists._id' => "54dc4fda0ac1f6a066a0646d"), array('$set' => array("lists.$.category" => '0')), true);