How can I update an element which is in a sublist of list by index?

Considering this sample scheme:
{
_id: “id”,
test: [ [“0”, “1”] , [“0”] ]
}

How can I update these elements by their position (index)? I use dot notation test.0 for the first level, I access the first sublist of the list, but how can I access the elements of this sublist?

Hello @BrainTrance_N_A, you can try this approach to update the nested array elements by the index:

db.collection.updateOne(
    { },
    { $set: { "test.1.0": "99" } }
)

This will update the test array field to: [ [ "0", "1" ], [ "99" ] ].

Hope this helps!

I’ve tried this approach but I get the error "Cannot create field " " in element " ".
I want to clarify that “test” is a nested field.
The first dot notation works, but not the second one.
{’$set’: {‘PARENT_TEST.$.test.0’: ‘99’} this doesn’t raise an error,
but this {’$set’: {‘PARENT_TEST.$.test.1.0’: “99”} does.

Sorry for not posting the actual data scheme, but it’s confusing because it’s embedded in Python code.

I suggest you include an example document if it has different structure than you had posted earlier.

Also, refer this in the manual about updating array fields:

This is the scheme:

{
  
  "id": "1",
  "name": "test",
  "vms": 
  [{
    "onoma": "nikolas",
    "plirwmi": [['0', '1'], ['0']]
    
  }]
  
}

“plirwmi” is the field of interest

@BrainTrance_N_A, you can do the update using the array update operator $[<identifier>] (the link I had provided has the documentation about “filtered positional operator”).

Note that you need to specify a condition to identify the element of the array field vms to update. I used the "onoma": "nikolas" as the filter criteria. The query:

db.collection.updateOne(
    {}, 
    { $set: { "vms.$[e].plirwmi.1.0": "99" } },
    { arrayFilters : [ { "e.onoma" : { $eq: "nikolas" } } ] }
)

This modifies "plirwmi": [ [ '0', '1' ], [ '0' ] ] to:
"plirwmi": [ [ '0', '1' ], [ '99' ] ]


EDIT ADD:

In the expression "vms.$[e].plirwmi.1.0", 1.0 represents the index positions of the array field plirwmi and the inner array. 1 is the second element of plirwmi array (index 1; array indexes start from 0). And, the 0 index is the inner array’s ([ '0' ] ) first element.

Although it works for the above scheme, it raises the same error in the original scheme which virtually has the same structure. I suppose I’ll have to check my code, something is different. In the context of the question your answer is an accepted solution. Thanks!

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.