douli1872
2016-01-18 10:04 阅读 88

修改嵌套数组中的字段值

{ 
    "_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"
                }
            ]
        }
    ]
}

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条回答 默认 最新

  • 已采纳
    dongzengzai4567 dongzengzai4567 2016-01-18 10:20

    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" } }
    )
    
    点赞 评论 复制链接分享

相关推荐