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

标签 python mongodb mongodb-query pymongo

我的集合结构如下:

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

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

我尝试过这个:

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

其中,data 是一个 JSON 对象,具有 _id 和字典 stuff 列表。运行此命令时,我收到了 OperationFailure: Thepositional Operator did not find the match required 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}})

关于python - 使用 PyMongo 更新集合中字典列表中的字典值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29191779/

相关文章:

mongodb - 将 ISO 日期转换为 yyyy-mm-dd 格式

python - mongodb findOne 和 $or 参数的顺序重要还是层次结构? [表现]

mongodb - 使用 $unwind 时可以避免两次使用相同的 $match 标准吗?

python - 尝试导入 Tensorflow 时出现 ModuleNotFoundError

mongodb - 如何搜索集合以在 MongoDB 中的文档之一中查找嵌套值

python - Pip:如何覆盖requirements.txt中的子依赖版本?

javascript从查询构建正则表达式

javascript - 如何将此 JSON 保存到 MongoDB Compass 提供服务的 mongoDB 数据库?

python - 使用 crontab/cron 安排 python 3.6 脚本

python - 多处理不使用所有内核