【问题标题】:Modify an element of an array inside an object in MongoDB修改MongoDB中对象内的数组元素
【发布时间】:2021-05-09 18:00:07
【问题描述】:

我有一些这样的文件:

doc = {
    "tag"   : "tag1",
    "field" : {
        "zone" :"zone1",
        "arr"  : [ 
            { vals: [-12.3,-1,0],     timestamp: ""},
            { vals: [-30.40,-23.2,0], timestamp: "" }
        ]
    }
}

我想修改其中一个文档的数组元素之一(例如,第一个元素,索引为 0 的元素)。

我想让它看起来像:

doc = {
    "tag"   : "tag1",
    "field" : {
        "zone" :"zone1",
        "arr"  : [ 
            { vals: [-1, -1, -1],       timestamp: "the_new_timestamp"},  // this one was modified
            { vals: [-30.40, -23.2, 0], timestamp: "" }
        ]
    }
}

我对@9​​87654325@有所了解:

db.mycollection.find_and_modify(
    query  = query,  // you find the document of interest with this
    fields = {  },  // you can focus on one of the fields of your document with this
    update = { "$set": data }, // you update your data with this
)

感觉更接近我想要的问题是:

我一直在研究它们,但在尝试为我的案例制定解决方案时遇到了困难。我不知道我是否真的应该使用fields 参数。我不知道如何正确使用$set

希望你能帮助我。

【问题讨论】:

  • 查询query = query是什么?如何判断需要修改哪个元素?
  • 哦,对了,我错过了。查询将过滤掉一个或多个文档,假设我只得到一个结果。然后我想通过它的索引选择一个数组元素。

标签: mongodb mongodb-query pymongo


【解决方案1】:

https://docs.mongodb.com/manual/reference/operator/update/positional/

这对你有帮助!

db.mycollection.updateOne(
   query,
   fields,
   { $set: { "field.arr.0.timestamp": "the_new_timestamp"} }
)

【讨论】:

  • 非常感谢,这正是我所需要的!顺便说一句,对于未来的用户。我没有使用“字段”。我不需要它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-29
  • 2012-01-17
  • 2016-11-05
相关资源
最近更新 更多