【问题标题】:Updating a value of dictionary in list of dictionaries in a collection using PyMongo使用 PyMongo 更新集合中字典列表中的字典值
【发布时间】:2015-03-22 06:51:10
【问题描述】:

我的集合结构如下:

defaultdict(
    lambda: {
        '_id' : None,
        'stuff' : [defaultdict(lambda : 0)]
    })

我正在尝试初始化一个我将继续更新的字典列表,如果字典的键已经存在,那么我会将其值增加 1,否则我将使用新的字典列表更新key, value 对。例如是stuff 的值是[] 并且我遇到了一个值val 然后stuff 的值将是[{'val' : 1}] 并且如果我得到一个值val2 然后stuff = [{'val' : 1}, {'val2' : 1}] 再如果我得到valstuff 应该是[{'val' : 2}, {'val2' : 1}]

我试过了:

table.update({'_id' : data['_id']}, \
             {'$inc' : {"stuff.$."+keyvalue : 1}})

其中,data 是一个 JSON 对象,具有一个 _id 和一个字典列表 stuff。运行这个我收到了OperationFailure: The positional operator did not find the match needed from the query

我不知道该怎么办?我是 Mongo 新手。

【问题讨论】:

  • 如果字典已经存在,那么我将其值更新为 1 是什么意思? keyvalue 是什么?你能证明使用你的文件吗?
  • @Michael 我已经用更好的解释更新了这个问题。我希望它能更好地了解我的要求?
  • 谢谢!我会运行它并让你知道。
  • 只要确保_id == data['_id']

标签: python mongodb mongodb-query pymongo


【解决方案1】:

引用documentation

与更新操作一起使用时,例如db.collection.update()db.collection.findAndModify()

  • 位置 $ 运算符充当与查询文档匹配的第一个元素的占位符,并且
  • 数组字段必须作为查询文档的一部分出现。

所以stuff 数组应该出现在您的查询中。现在,由于您正在进行条件更新,您需要使用$exists 检查您的数组是否已经有任何带有keyvalue 的子文档。

if not table.find_one({ "_id": data['_id'], "stuff": {"$elemMatch": {keyvalue: { "$exists" : True }}}}):
    table.update({ "_id": data['_id'] }, { "$push": { "stuff": { keyvalue: 1 }}})
else:
    table.update({ "_id": data['_id'], "stuff": { "$elemMatch": { keyvalue: { "$exists" : True}}}}, { "$inc": { "stuff.$." + keyvalue: 1}})

【讨论】:

  • 在第一部分我还应该添加{upsert : True}吗?
  • 为什么会想要那个?你不需要
猜你喜欢
  • 2021-10-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-06
  • 2019-02-21
相关资源
最近更新 更多