Search code examples
mongodbupdatesaws-documentdb

Mongodb aggregate update field in sub array


First of all, I'm using DocumentDB from AWS, so I've not all MongoDB functions.

I have these records:

{
    "_id" : ObjectId("609be32555c7753b0cb21fsd"),
    "validaProdutos" : [ 
        {
            "atributos" : [ 
                {
                    "codigo" : "seller",
                    "valores" : []
                }
            ]
        }
    ],
},
{
    "_id" : ObjectId("609be32555c7753b0cb20edc"),
    "validaProdutos" : [ 
        {
            "atributos" : [ 
                {
                    "codigo" : "brand",
                    "valores" : []
                }
            ]
        }
    ],
},
{
    "_id" : ObjectId("609be32555c7753b0cb32123"),
    "validaProdutos" : [ 
        {
            "atributos" : [ 
                {
                    "codigo" : "seller",
                    "valores" : []
                }
            ]
        }
    ],
}

And I need to update validaProdutos.atributos.codigo to "done" when validaProdutos.atributos.codigo === "seller"

I've tried so many things, but the last try was:

db.col1.aggregate([
{ 
    "$addFields": { 
        "validaProdutos.atributos": {
            $filter: {
                input: "$validaProdutos.atributos",
                as: "item",
                cond: [{ $eq: ["$$item.codigo", "seller"] }, "done", "$$item.codigo"]
            }
        }
    },
    { $out: "col1" } 
},
])

But it doesn't works, just get a list not modified.

Somebody helps?


Solution

  • You should use update method with arrayFilters and multi equals true, to affect all documents in your collection:

    https://mongoplayground.net/p/Ln2qMCm9GMB

    db.collection.update(
      {},
      {
        $set: {
          "validaProdutos.$[].atributos.$[a].codigo": "done",
        },
      },
      {
        multi: true,
        arrayFilters: [
          {
            "a.codigo": "seller",
          },
        ],
      }
    );