我想在嵌套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不存在时,就会创建它,并且一切正常,直到它第二次尝试增加某个内容,然后它再次崩溃
我以前的代码并不总是正常工作
我建议使用“复杂”的方法:
或集合,如果需要同时更新多个类别:
相关问题 更多 >
编程相关推荐