python - 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 与负整数一起使用吗?还是我的查询错误?
更新:当“类别”字典在运行查询之前不存在时,它被创建并且一切正常,直到它尝试第二次增加某些东西,然后它再次崩溃。
解决方案
我以前的代码并不总是能正常工作。
我建议使用“复杂”的方法:
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
推荐阅读
- java - 凌空得到响应前的响应时间
- reactjs - Laravel 中的授权 AJAX 请求
- android - 如何在Android中处理写入BluetoothSocket的OutputStream?
- stripe-payments - 当条带计费周期锚点位于第 31 年或闰年时会发生什么?
- excel - 如何解决命名冲突的VB编辑器中代码的自动大写?
- r - 不按字母顺序进行组合
- python - Matplotlib 图到轴
- python-3.x - 使用 Python 在特定行中删除具有特定字符串的列
- html - 为什么带有文本的 div 不适合文本尺寸?
- python - 根据存在 Pandas 添加行