【问题标题】:Update single array item with matching id and one of the array element using Pymongo使用 Pymongo 更新具有匹配 id 和数组元素之一的单个数组项
【发布时间】:2020-11-17 18:50:36
【问题描述】:

使用 Pymongo 更新具有匹配 id 和数组元素之一的单个数组项

使用 array_filters 尝试了几个 Pymongo 命令(不确定这是否仅适用于 1 个数组级别深度),但看起来没有任何更新,即使没有报告错误但更新没有发生。

更新以下内容的正确 Pymongo 命令是什么?

{
        "_id" : ObjectId("9f1a5aa4217d695e4fe56be1"),
    
        "array1" : [
                {
                        "user" : "testUser1",            
                        "age" : 30,                    
                }
        ],
}
new_age_number = 32
mongo.db.myCollection.update_one({"_id": id}, {"$set": {"array1.$[i].age": new_age_number}}, array_filters=[{"i.user":"testUser1"}],upsert=False)


update_db = mongo.db.myCollection.update({"_id": id, "array1[index].user":"testUser1"}, {"$set": {"item_list[index].age": new_age_number}}, upsert=False)

mongo.db.myCollection.save(update_db)

*index 是 for 循环中的数字

【问题讨论】:

    标签: mongodb pymongo pymongo-3.x flask-pymongo


    【解决方案1】:

    在此处查看文档:https://docs.mongodb.com/manual/reference/operator/update/positional/#update-documents-in-an-array

    特别注意:

    重要

    您必须将数组字段作为查询文档的一部分。

    所以,如果要更新数组中的第一项:

    oid = ObjectId("9f1a5aa4217d695e4fe56be1")
    db.mycollection.update_one({'_id': oid, 'array1.user':  'testUser1' }, {'$set': {'array1.$.age': 32}})
    

    如果要更新数组中的特定项:

    oid = ObjectId("9f1a5aa4217d695e4fe56be1")
    db.mycollection.update_one({'_id': oid, 'array1': {'$elemMatch': { 'user':  'testUser1' }}}, {'$set': {'array1.$.age': 32}})
    

    【讨论】:

    • db_update=db.mycollection.update_one({'_id': oid, 'array1': {'$elemMatch': { 'user': 'testUser1' }}}, {'$set' : {'array1.$.age': 32}})
    • 我看到 db_update.raw_result 有这个值 {'n': 1, 'nModified': 1, 'ok': 1.0, 'updatedExisting': True}
    • - DB 未使用新值进行更新。我在这里错过了什么吗?
    • 是的。这是正确的数据库。我相信 update_one 保存它并且不附加 mongo.db.myCollection.save() 函数。
    • 正确,你不需要.save()
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-21
    • 1970-01-01
    • 2016-08-18
    相关资源
    最近更新 更多