Čamo
Čamo

Reputation: 4182

Mongodb $group + array items count

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.

Upvotes: 1

Views: 695

Answers (2)

d4v1d
d4v1d

Reputation: 351

have you try with aggregation?

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

Upvotes: 0

Jiří Pospíšil
Jiří Pospíšil

Reputation: 14412

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

{
  $group: {
    _id: "$A",
    countB: {
      $sum: {
        $size: "$B"
      }
    }
  }
}

Upvotes: 6

Related Questions