使用 PyMongo 更新集合中字典列表中的字典值

Updating a value of dictionary in list of dictionaries in a collection using PyMongo

我的集合结构如下:

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新手

引用 documentation

When used with update operations, e.g. db.collection.update() and db.collection.findAndModify(),

  • the positional $ operator acts as a placeholder for the first element that matches the query document, and
  • the array field must appear as part of the query document.

因此 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}})