首页 > 解决方案 > Updating array in pymongo

问题描述

I am trying to maintain some counters in mongodb, so I need to update them periodically. I had the code working correctly when the data structure was a single level:

mlcol.find_one_and_update({"connip": conip}, {"$inc":{ts:1}}, upsert=True)

This resulted in an structure like this:

{
    "connip": "a",
    "1":1,
    "2":1,
    "3":1,
    "4":1
}

I want to convert the data structure to something like this:

{
    "connip": "a",
    "timeline": [
        {
            "timeslot": "1",
            "counter": 1
        },
        {
            "timeslot": "2",
            "counter": 1
        }
    ]
}

When I send this command:

mlcol.find_one_and_update({"connip": "a", "timeline.timeslot": "c"}, {"$inc":{"timeline.$.counter":1}}, upsert=True)

I get a correct update of the already existing counters, but If it is a new one, I get the following error:

pymongo.errors.OperationFailure: The positional operator did not find the match needed from the query.

It seems that it is necessary to first launch the insetr_one command:

ne = {"connip": "a","timeline":[{"timeslot": "c","counter":1},{"timeslot": "d","counter":1}]}
mlcol.insert_one(ne)

Is there any way of forcing the creation of the counter in case of this not existing previously? It is something that the command in the flat structure does correctly.

标签: pythonmongodbpymongo

解决方案


推荐阅读