首页 > 解决方案 > PyMongo 查询问题:递增嵌套的 dict 条目

问题描述

我想在嵌套字典中增加一个条目。我发现嵌套字典的符号是“firstdict.second”。但在我的情况下,“第二个”是一个变量,所以我像这样预先构建查询:

cat_query = 'categories.' + category           # build the query for the nested dict
query = {'$inc': {cat_query: trans['amount']}} # build the rest of the increment query
# exectue the query
db.months.update_one({'year': trans['date'].year, 'month': trans['date'].month}, query) 

最后query应该看起来像例如{'$inc': {'categories.food': -300}} 每次我尝试运行查询时,mongodb 都会崩溃。日志说:

得到信号:7(总线错误)。

问题出在哪里?我不能将 $inc 与负整数一起使用吗?还是我的查询错误?

更新:当“类别”字典在运行查询之前不存在时,它被创建并且一切正常,直到它尝试第二次增加某些东西,然后它再次崩溃。

标签: pythonmongodbmongodb-querypymongo

解决方案


我以前的代码并不总是能正常工作。

我建议使用“复杂”的方法:

old_value = db.months.find_one({'year': trans['date'].year, 'month': trans['date'].month})["categories"][category]
query = {'$set': {"categories": {category: old_value + trans['amount']} }}

或集合,如果您需要一次更新多个类别:

from collections import Counter 
old_amounts = Counter(db.months.find_one({'year': trans['date'].year, 'month': trans['date'].month})["categories"]) # dict to Counter
now_amounts = Counter({"category_1": trans['amount_1'], "category_2": trans['amount_2'],"category_n": trans['amount_n']}) # dict to counter
new_amounts = dict(old_amounts + now_amounts) # counter to dict
query = {'$set': {"categories": new_amounts }} # update categories dict in document

推荐阅读