doujing5435 2016-09-21 10:55
浏览 97
已采纳

如何更新MongoDB文档中的数组元素

I've got a problem updating an array element in MongoDB. This is the structure of a document:

{
        "_id" : ObjectId("57e2645e11c979157400046e"),
        "site" : "BLABLA",
        "timestamp_hour" : 1473343200,
        "values" : [
                {
                        "1473343200" : 66
                },
                {
                        "1473344100" : 230
                },
                {
                        "1473345000" : 479
                },
                {
                        "1473345900" : 139
                }
        ]
}

Now I want to update the element with key "1473345900". How can I do this? I've tried:

db.COLLECTIONNAME.update({"values.1473345900": {$exists:true}}, {$set: {"values.$": 0}})

But after that the document looks like:

{
        "_id" : ObjectId("57e2645e11c979157400046e"),
        "site" : "BLABLA",
        "timestamp_hour" : 1473343200,
        "values" : [
                {
                        "1473343200" : 66
                },
                {
                        "1473344100" : 230
                },
                {
                        "1473345000" : 479
                },
                0
        ]
}

What I'm doing wrong? I only want to update the value of 1473345900 to any value... I don't want to update the complete element...

Thanks a lot!!!

  • 写回答

1条回答 默认 最新

  • donglu5041 2016-09-21 11:29
    关注

    You need to add an additional query in your update that matches the array element you want to update. A typical query would involve checking for the element's value not equal to the one being updated.

    The following example update shows this where the $ positional operator identifies the correct index position of the hash key array element { "1473345900": 139 }. If you try to run the update operation without the $ positional operator:

    db.COLLECTIONNAME.update(
        { "values.1473345900": { "$exists": true } }, 
        { "$set": { "values.1473345900": 0 } }
    )
    

    mongo will treat the timestamp 1473345900 as the index position and thus you will get the error

    can't backfill array to larger than 1500000 elements

    Thus the correct way should be:

    var val = 32;   
    db.COLLECTIONNAME.update(
        { "values.1473345900": { "$ne": val, "$exists": true } },
        { "$set": { "values.$.1473345900": val } }
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划