Upserting subdocumets as a list with mutate_in

Viewed 105

Would really appreciate your help here.

I am trying to mutate the sub documents by using mutate_in and then defining the SD with a path for each element that I want to put in. The code looks like this:

cb.mutate_in(‘1_2’,
SD.upsert(
‘strat.a’, 76543, create_parents=True),
SD.upsert(
‘strat.b’, “true”, create_parents=True),
SD.upsert(
‘strat.c’, 30, create_parents=True),
SD.upsert(
‘strat.d’, -25, create_parents=True),
SD.upsert(
‘strat.e’, “C”, create_parents=True),
SD.upsert(
‘strat.f’, 7, create_parents=True),
)

This is the kind of result it brings in:

{
“strat”: {
“a”: 76543,
“b”: “true”,
“c”: 30,
“d”: -25,
“e”: “C”,
“f”: 7
}
}

What I am looking for is this (Notice that I am putting that in a list here):

{
“Strat”: [
{
“a”: “12345”,
“b”: 7,
“c”: “C”,
“d”: “true”,
“e”: -25,
“f”: 25
}
]
}

Once I am able to achieve the above as a list, I should be able to generate multiple sub documents like this:

Notice that now I have 2 elements in this list both having different values:

{
“Strat”: [
{
“a”: “12345”,
“b”: 7,
“c”: “C”,
“d”: “true”,
“e”: -25,
“f”: 25
},
{
“a”: “34567”,
“b”: 8,
“c”: “F”,
“d”: “false”,
“e”: -30,
“f”: 40
}
]
}

QUESTION:

can I achieve this with mutate_in and SD.upsert ?
if so, how can I change that code I have provided at the beginning of this thread to put things in a list
Once I can put it as a list, how can I avoid upsert not overwriting the record but to attach another record in that list?

Your help is highly appreciated. Thank you !

Looking forward to some direction from all the couchbase gurus out there

1 Answers

You can create a Python Dictionary representing the new JSON Object, and append it to the array (create_parents=True says "create the array if it doesn't already exist").

I am not fluent in Python, and have no idea if this compiles... so let's call it pseudocode :-)

cb.mutate_in(‘1_2’,
    SD.array_append('strat',
        {
            "a": "12345",
            "b": 7,
            "c": "C",
            "d": "true",
            "e": -25,
            "f": 25
        },
        create_parents=True),
   
    SD.array_append('strat',
        {
            // some other values...
        },
        create_parents=True));

You can append up to 16 items at a time this way (subdoc batches are limited to 16 operations).

Related