修改嵌套数组中的字段值

时间:2016-01-18 10:04:51

标签: php arrays mongodb nested

{ 
    "_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至少进行吗?

谢谢

1 个答案:

答案 0 :(得分:1)

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

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

在MongoDB中,这应该是这样的。我假设您需要更新子文档的条件,因此我使用了用户名 Vipul

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