2

I am working in a project with express and mongodb (I am using mongoose) and I have a collection whith the following structure:

[
{
    "_id": "5e4a39f01ab49e48d4db5b9c",
    "last": {
        "winningNumbers": {
            "list": [
                66,
                71,
                62,
                50,
                29,
                67,
                74,
                43,
                22,
                1,
                11,
                3,
                80,
                17,
                57,
                53,
                30,
                19,
                76,
                40
            ],
            "bonus": [
                40
            ]
        }
    }
},
{
    "_id": "5e4a3b1c1ab49e48d4db5cb8",
    "last": {
        "winningNumbers": {
            "list": [
                71,
                46,
                79,
                60,
                1,
                14,
                19,
                73,
                34,
                55,
                5,
                65,
                12,
                47,
                16,
                62,
                51,
                53,
                3,
                45
            ],
            "bonus": [
                45
            ]
        }
    }
}

]

I have tried to use the mongodb aggregation framework to count the occurrences of each number in the last.winningNumber.list array in the whole collection but I did not achieved that.

I want to have as ouput something like below:

{
    "occurrences": [
        {number:1,count:3},
        {number:2,count:8},
        {number:12,count:15},
        ...
        {number:78,count:55},
    ]
}

Is there any way to achieve that using $group or should I use something different?

Thank you!

1 Answer 1

3

$group is the way to achieve this, but you have to $unwind your array before.

db.collection.aggregate([
  {
    $project: {
      "last.winningNumbers.list": 1
    }
  },
  {
    $unwind: "$last.winningNumbers.list"
  },
  {
    $group: {
      _id: "$last.winningNumbers.list",
      count: {
        $sum: 1
      }
    }
  }
])

Note : the first $project stage is not mandatory, and it will produce exactly the same result without it. However, I higly recommand to keep it on place, as unwinding / grouping can be expensive operations. (it will produce one document per array element).

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

1 Comment

Thank you! I have already dane it with the same way. That helps me a lot!

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.