my collection Data is like this:
[
{ "_id": 1, "s": "a", "kc": 100 },
{ "_id": 2, "s": "a", "kc": 101 },
{ "_id": 3, "s": "a", "kc": 102 },
{ "_id": 4, "s": "a", "kc": 103 },
{ "_id": 5, "s": "b", "kc": 200 },
{ "_id": 6, "s": "b", "kc": 201 },
{ "_id": 7, "s": "b", "kc": 202 },
{ "_id": 8, "s": "b", "kc": 203 }
]
I use this aggregation:
db.collection.aggregate([
{
"$group": {
_id: "$s",
kcList: {
"$push": "$kc"
}
}
}
])
and the result was as below:
[
{
"_id": "a",
"kcList": [
100,
101,
102,
103
]
},
{
"_id": "b",
"kcList": [
200,
201,
202,
203
]
}
]
I want to change my Query In a way that when grouping data in kcList, each item multiplied to its array index.
I want the result as below:
[
{
"_id": "a",
"kcList": [
100 * 0,
101 * 1,
102 * 2,
103 * 3
]
},
{
"_id": "b",
"kcList": [
200 * 0,
201 * 1,
202 * 2,
203 * 3
]
}
]
so I wrote this query:
db.collection.aggregate([
{
"$group": {
_id: "$s",
kcList: {
"$push": {
"$multiply": [
"$kc",
{
$cond: {
if: {
$isArray: "$kcList"
},
then: {
$size: "$kcList"
},
else: 0
}
}
]
}
}
}
}
])
But the result is wrong:( do you have any idea to solve this?
100 * 0,101 * 1?