1

I need to $group Mongodb data according field A and the result should contain the count of field B items which is array. For example if data looks like:

{A: 1, B: [1, 2, 3]}
{A: 1, B: [4, 2]}
{A: 2, B: [1]}
{A: 2, B: [2, 3]}
{A: 2, B: [1, 2, 3]}

the result should look like:

{A: 1, countB: 5}
{A: 2, countB: 6}

I have a solution with $unwind like:

[
    {
        $unwind: "$B"
    },
    {
        $group: {
            "_id": "$A",
            "countB": {$sum: 1}
    },
    {
        $project: {
            "_id": 0,
            "A": "$_id.A",
            "countB": "$countB"
        }
    }    
]

My question is if it is possible to do it without $unwind stage?

Thank you.

2 Answers 2

6

You can use the $size operator to get the length the individual arrays.

{
  $group: {
    _id: "$A",
    countB: {
      $sum: {
        $size: "$B"
      }
    }
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

This is it. Thank you.
0

have you try with aggregation?

db.collection.aggregate([{$project: {
"A": "$A",
  count: {
    $size: "$B"
  }
}}])

4 Comments

This query produces an error: mongoplayground.net/p/PjPV0XK_WsN
Sorry, just change $group to $project
Where is $group?
@Čamo I already edited it, so you can just use that without any error

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.