douli1872 2016-01-18 10:04
浏览 190
已采纳

修改嵌套数组中的字段值

{ 
    "_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 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" } }
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来