Update dict items inside an array

I have an specific scenery where we buy same products from different vendors, then i’m saving product values inside the client. This is working, but when i try to update, those values are overwrite by the ‘new’ dict.

{
    "_id": 3,
    "nome": "Cliente De Teste",
    "grupo": "Grupo Teste",
    "fiscal": "T1",
    "cnpj": "xx.xxx.644/0001-81",
    "produtos": [
        {
            "1": {
                "produto": "Brita 3/4 Rosa",
                "filial": "1",
                "valor": "1.11",
                "frete": "1.11",
                "total": "2.22"
            },
            "2": {
                "produto": "Brita 3/4 mesclada",
                "filial": "1",
                "valor": "1.11",
                "frete": "1.11",
                "total": "2.22"
            }
        }
    ],
    "tipo": "Concreteira",
    "cidade": "Criciuma",
    "estado": "ES",
    "cep": "95xxxx-000",
    "email": "admin@admin.com",
    "telefone": "(48) xxxx-9081"
}

I want update the ‘produtos’ by its id (“1”, “2”). This is my query which is overwriting:

clientesdb.update_one({"_id": int(client_id[1])},
    {'$set': {'produtos': {
        str(produto_field[0]): 
            { 
            "produto": str(produto_field[1]),
            "filial":str(produto_field[2]), 
            "valor":str(form.valor.data),
            "frete":str(form.frete.data),
            "total": str(total),
            }
    }}})

When you do

{$set:{produtos:AnyValue}}

you asked to change the field produtos to AnyValue, so effectively you asked to change the whole array to the object

You need to be more specific using the dot notation. In your case you want to change the object produto_field[0] of the first object of the array produtos. The way you specify this is with

{ "$set" : { "produtos.0." + produto_fields[0] :
  {
  "produto" : str( ... ) ,
  ...
  "total" : str( ... ) ,
  }
} }
1 Like

Thank you kind sir. I’m fighting this issue for two full days! I just had to do a small change

{ "$set" : { "produtos."+produto_fields[0] -1+"." + produto_fields[0] :
  {
  "produto" : str( ... ) ,
  ...
  "total" : str( ... ) ,
  }
} }

Since my _ids start from 1. Thank you very much :slight_smile:

1 Like

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