I have this collection on Mongodb:
[
{
_id: new ObjectId("630954ebdfec2657ac6086e5"),
productos: [ [Object], [Object] ],
timestamp: 2022-08-26T23:19:07.321Z,
__v: 0
}
]
and i would like to know how can i sum the "cantidad" value inside "productos" array.
"productos" looks like this:
[
{
nombre: 'sandia',
foto: 'https://cdn3.iconfinder.com/data/icons/fruits-52/150/icon_fruit_melancia-128.png',
precio: 12,
cantidad: 1,
_id: new ObjectId("62fc0daf755a14dbac449005")
},
{
nombre: 'frutillas',
foto: 'https://cdn3.iconfinder.com/data/icons/fruits-52/150/icon_fruit_morango-128.png',
precio: 15,
cantidad: 1,
_id: new ObjectId("62fc14badcaffc2a39ab7b46")
}
]
Any help would be appreciated.
happy coding!
CodePudding user response:
You don't specify what you want the output to look like, so this just "$project"
s a new field with the sum.
db.collection.aggregate([
{
"$project": {
"cantidadSum": {
"$sum": "$productos.cantidad"
}
}
}
])
Example output:
[
{
"_id": ObjectId("630954ebdfec2657ac6086e5"),
"cantidadSum": 2
}
]
Try it on mongoplayground.net.
CodePudding user response:
Oh!, sorry! What i want for output would be the object with the "cantidad" (quantity in spanish) sum 1
Sorry my english!
something like this with the quantity modified:
{nombre: 'sandia',
foto: 'https://cdn3.iconfinder.com/data/icons/fruits-52/150/icon_fruit_melancia-128.png',
precio: 12,
cantidad: 2,
_id: new ObjectId("62fc0daf755a14dbac449005")}
Regards!