修改嵌套数组中的字段值

Modify Field Values in a Nested Array

{ 
    "_id" : ObjectId("568501dd4b1eaa529a40c3b7"), 
    "Thought" : [
        {
            "thread_id" : "f6a678ed8e45ab22f258020530ddaafc", 
            "th_username" : "Vipul", 
            "th_email" : "abc@abc.com", 
            "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" : "abc@abc.com", 
                    "comment_txt" : "hello comment", 
                    "cmt_likes" : 2.0, 
                    "cmt_liked_user" : [

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

这是我的文档,我想将 Thought.Comments.cmt_likes 从 2.0 替换为我想要的东西(例如 4.0)

我不能使用 $ 运算符两次,所以我不能使用 $inc 来增加值。

有什么方法可以修改嵌套数组字段吗? 如果不可能,那么我至少可以通过 php 完成吗?

谢谢

在 PHP 中,您可以像这样访问该值,假设您已将其存储在变量 $mydoc:

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

在MongoDB中,应该是这样的。我假设您需要 sub-documents 更新的条件,所以我为此使用了用户名 Vipul

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