1

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?

Mongo playground

2
  • The expected output which you provided is not clear. what do you mean by 100 * 0, 101 * 1? Commented Jun 8, 2021 at 9:05
  • 100 , 101 , 102 , 103 is the 'kc' value and 0 , 1 , 2 , 3 is the array item index Commented Jun 8, 2021 at 9:10

1 Answer 1

1

Add new stage after group stage,

  • $range to create an array of numbers from 0 to length of kcList array using $size
  • $map to iterate loop of the above range
  • $arrayElemAt to get element of range position in kcList array
  • $multiply to multiply range number with kcList value returned from the above operation
db.collection.aggregate([
  {
    $group: {
      _id: "$s",
      kcList: { $push: "$kc" }
    }
  },
  {
    $project: {
      kcList: {
        $map: {
          input: { $range: [0, { $size: "$kcList" }] },
          in: {
            $multiply: [
              { $arrayElemAt: ["$kcList", "$$this"] },
              "$$this"
            ]
          }
        }
      }
    }
  }
])

Playground

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.