我试图在mongodb中维护一些计数器,因此需要定期更新它们。当数据结构为单级时,我让代码正常工作:
mlcol.find_one_and_update({"connip": conip}, {"$inc":{ts:1}}, upsert=True)
这就形成了这样的结构:
{
"connip": "a",
"1":1,
"2":1,
"3":1,
"4":1
}
我想把数据结构转换成这样:
{
"connip": "a",
"timeline": [
{
"timeslot": "1",
"counter": 1
},
{
"timeslot": "2",
"counter": 1
}
]
}
当我发出这个命令时:
mlcol.find_one_and_update({"connip": "a", "timeline.timeslot": "c"}, {"$inc":{"timeline.$.counter":1}}, upsert=True)
我得到已存在计数器的正确更新,但如果是新计数器,则会出现以下错误:
pymongo.errors.OperationFailure: The positional operator did not find the match needed from the query.
似乎有必要首先启动insertèone命令:
ne = {"connip": "a","timeline":[{"timeslot": "c","counter":1},{"timeslot": "d","counter":1}]}
mlcol.insert_one(ne)
如果以前不存在这种情况,有没有办法强制创建计数器?这是平面结构中的命令正确执行的操作。你知道吗
目前没有回答
相关问题 更多 >
编程相关推荐