PyMongo查询问题:增加嵌套dict条目

2024-09-29 21:37:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在嵌套dict中增加一个条目。我发现嵌套dict的符号是“firstdict.second”。但是“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都会崩溃。日志上写着:

Got signal: 7 (Bus error).

问题出在哪里?我不能用带负整数的$inc吗?还是我的问题错了

更新:在运行查询之前,当“categories”dict不存在时,就会创建它,并且一切正常,直到它第二次尝试增加某个内容,然后它再次崩溃


Tags: thebuildtransdate符号条目queryyear
1条回答
网友
1楼 · 发布于 2024-09-29 21:37:38

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

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

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

相关问题 更多 >

    热门问题