Skip to content

Instantly share code, notes, and snippets.

@Tsugami
Last active December 3, 2021 15:39
Show Gist options
  • Save Tsugami/6531f4a3ac864388c667a2c06a20593d to your computer and use it in GitHub Desktop.
Save Tsugami/6531f4a3ac864388c667a2c06a20593d to your computer and use it in GitHub Desktop.
MONGO - calculate the total of items from one array and another from another array
// Data
// [
// {
// "key": 1,
// "seasons": [
// {
// episodes: [
// 3,
// 3
// ]
// },
// {
// episodes: [
// 3,
// 3,
// 1
// ]
// },
// ]
// },
// {
// "key": 2,
// "seasons": [
// {
// episodes: [
// 3,
// 3
// ]
// }
// ]
// },
// {
// "key": 1,
// "seasons": [
// {
// episodes: [
// 3,
// 3
// ]
// }
// ]
// }
// ]
db.collection.aggregate([
{
"$match": {
key: 1
}
},
{
"$unwind": "$seasons"
},
{
"$group": {
"_id": null,
"count": {
$sum: {
$size: "$seasons.episodes"
}
}
}
}
])
// [
// {
// "_id": null,
// "count": 7
// }
// ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment