Operaciones al iterar en un arreglo con documentos

Una duda de MongoDB, alguien ha hecho operaciones con campos dentro de un documento que está embebido en un arreglo de documentos?, ejemplo: [{“Precio”:12, “cantidad”:3}, {“Precio”:12, “cantidad”:3},…], buscó multiplicar Precio *cantidad en cada elemento del arreglo, y sumar sus productos respectivos.


1 Like

Ya logré hacer la operación, sacando la lista de objetos con $unwind, y agrupando estos objetos con $group, una vez agrupados, realicé la suma con $sum, y a su vez pude multiplicar por cada documento los campos “Precio” y “cantidad”. ¿alguien sabe como puedo actualizar el documento inicial con el resultado de la opción descrita previamente?. ¡Saludos!

@Stennie can you help me help on this? @Emmanuel_Diaz writes:

I managed to derive the list of objects via $unwind, and group these objects via $group, and once they were grouped, extract the sum using $sum, and then for each document multiply the field Precio (Price) by cantidad (Quantity). Can someone tell me how to update the original document with the result of the operation described? Thanks!

1 Like

Hola @Emmanuel_Diaz! (and thanks for the translation @Jack_Woehr!)

It would be very helpful to have more specific details such as your version of MongoDB server, sample documents, and aggregation pipeline in order to provide relevant suggestions.

However, for general approaches to saving documents manipulated by aggregation back to the original collection consider:

  • MongoDB 4.2+ supports an aggregation $merge stage which outputs results to a collection with options for how to merge when a result document matches an existing document in the output collection.

  • You can iterate the aggregation result cursor in your application code and perform the equivalent logic of $merge by saving updates to affected documents (possibly as a bulk write if you have many document updates). This is an option for any version of MongoDB that supports your aggregation pipeline features, but adds some overhead for fetching aggregation results over the network and then sending them back to your MongoDB deployment.

  • MongoDB 4.2+ also supports Updates with Aggregation Pipeline with a limited selection of stages. Based on your description of unwinding & grouping this may not be suitable for your current aggregation pipeline usage, but I’m listing here for completeness.