【问题标题】:update an element of an array in mongo collection based on a condition met by another element in the same array根据同一数组中另一个元素满足的条件更新 mongo 集合中数组的元素
【发布时间】:2021-06-02 12:26:00
【问题描述】:

以下是我的收藏。

{
'_id': ObjectId('603fd4575250717d17aba89e'),
'user_id': 19,
'items': [
{

'price': 5,
'id': '342566b0d5f14117a228d8b17f215c4a'
},


 {


 'price': 5,
 'id': '09e12c647fdf4c409e934eac23c73789'
}
],

  }

我需要更新 id 为 09e12c647fdf4c409e934eac23c73789 的元素的价格,它的当前值为 5,我需要将其更新为 6,请问是否知道相同的查询。

我尝试了以下查询,但没有成功。

a = db.sample_collection.update_one({"items.$.id": "09e12c647fdf4c409e934eac23c73789"}, 
{"$set": {"items.$price": 6}})

有人可以帮我解决正确的查询吗?

【问题讨论】:

    标签: mongodb pymongo pymongo-3.x


    【解决方案1】:

    更新查询应如下所示:

    a = db.sample_collection.update_one({"items.id": "09e12c647fdf4c409e934eac23c73789"}, { "$set": { "items.$.price": 6 }})
    

    这是updating a document in an array 的示例。执行更新时,positional operator, $ 应该只出现在更新文档中,而不是查询文档中。

    【讨论】:

    • 谢谢你的回答:)
    猜你喜欢
    • 2015-08-30
    • 1970-01-01
    • 2020-03-19
    • 2018-07-26
    • 1970-01-01
    • 1970-01-01
    • 2021-06-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多