Vipul Masurkar
Vipul Masurkar

Reputation: 25

Modify Field Values in a Nested Array

{ 
    "_id" : ObjectId("568501dd4b1eaa529a40c3b7"), 
    "Thought" : [
        {
            "thread_id" : "f6a678ed8e45ab22f258020530ddaafc", 
            "th_username" : "Vipul", 
            "th_email" : "[email protected]", 
            "th_text" : "original thought", 
            "th_image" : "", 
            "likes" : NumberInt(0), 
            "liked_user" : [], 
            "th_inserted_at" : "18-01-2016 13:31:45", 
            "Comments" : [
                {
                    "comment_id" : "f30937a4e12b0b7c975c172767ce7713", 
                    "cmt_from_id" : "5509dc6dcf5b5b7b8f95f23f041886d3", 
                    "commenter_name" : "Vipul Masurkar", 
                    "commenter_email" : "[email protected]", 
                    "comment_txt" : "hello comment", 
                    "cmt_likes" : 2.0, 
                    "cmt_liked_user" : [

                    ], 
                    "cmt_inserted_at" : "18-01-2016 13:31:54"
                }
            ]
        }
    ]
}

This is my Document and I want to replace Thought.Comments.cmt_likes from 2.0 to something of my wish (eg 4.0)

I can't use $ operator twice so I can't use $inc to increment the value.

Is there any way to modify the nested array fields? If not possible then can I do it through php atleast?

Thank You

Upvotes: 0

Views: 105

Answers (1)

trincot
trincot

Reputation: 350272

In PHP you can access that value like this, assuming that you have it stored in variable $mydoc:

$mydoc->Thought[0]->Comments[0]->cmt_likes = '4.0';

In MongoDB, this should be something like this. I assumed you would need a condition which sub-documents to update, so I used the username Vipul for that:

db.mydb.update(
    { "Thought.0.th_username": "Vipul" },
    { $set: { "Thought.0.Comments.0.cmt_likes": "4.0" } }
)

Upvotes: 1

Related Questions