我的集合结构如下:
defaultdict(
lambda: {
'_id' : None,
'stuff' : [defaultdict(lambda : 0)]
})
我正在尝试初始化一个字典列表,我将继续更新该列表,如果字典的键已经存在,那么我会将其值增加 1,否则我将用新的字典更新列表键,值
对。例如stuff
的值是 [] 并且我遇到了一个值 val
那么 stuff
的值将是 [{' val' : 1}]
如果我得到一个值 val2
则 stuff = [{'val' : 1}, {'val2' : 1}]
,如果我得到 val
,stuff
应该是 [{'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 新手。
最佳答案
When used with update operations, e.g.
db.collection.update()
anddb.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/