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

1 Answer 1

1

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" } }
)
Sign up to request clarification or add additional context in comments.

3 Comments

if i loop through the Comments array and find cmt_likes your way and modify the data then how would i commit the changes back to the document without changing the order of the Comments array
thanks i am almost there but i dont know the index specifically.. can you give me a solution using a loop where updae only happens to the right cmt_likes field as the comments array may increase with time
Maybe you can be more specific about which conditions must be true for an update to happen.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.