J
J
Jolt2020-11-16 20:44:16
Python
Jolt, 2020-11-16 20:44:16

How to add a structure to an array or update an existing element?

For example, there is the following object in the database.

{
    "visitor_id": 1,
    "counter": [
        {
            "name": "foo",
            "value": 20
        },
        {
            "name": "bar",
            "value": 35
        }
    ]
}

it is necessary to write a new value to the counter
array, if such counter.name already exists, then increment counter.value ,
otherwise add a new structure to the array.
1) For example after recording:
{
    "name": "bar",
    "value": 2
}

The structure will look like this:
{
    "visitor_id": 1,
    "counter": [
        {
            "name": "foo",
            "value": 20
        },
        {
            "name": "bar",
            "value": 37
        }
    ]
}

2) And after recording:
{
    "name": "foobar",
    "value": 3
}

Look like this:
{
    "visitor_id": 1,
    "counter": [
        {
            "name": "foo",
            "value": 20
        },
        {
            "name": "bar",
            "value": 35
        },
        {
            "name": "foobar",
            "value": 3
        }
    ]
}


PS: I've been reading Mongi for a long time, usually I quickly understand what is written, but then something didn't work.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Philipp, 2020-11-16
@zoonman

https://docs.mongodb.com/manual/reference/operator...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question