Rafa Acioly
Rafa Acioly

Reputation: 636

How to group mongo result for specific keys?

I've a collection that has this documents:

{name: "x", code: 1},
{name: "x", code: 2},
{name: "x", code: 3},
{name: "x", code: 1}

How can i group and count the keys that are equal to 1 and what is not equal to 1? I manage to group by the code but the result comes separately for 1, 2 and 3

aggregate([
    {'$match': {'name': "x"}},
    {'$group': {'_id': '$code', 'total': {'$sum': 1}}},
    {'$sort': {'_id': 1}}
])

Upvotes: 0

Views: 29

Answers (2)

prasad_
prasad_

Reputation: 14287

Aggregation with $facet allows you to query on same set of documents in multiple facets. You can the desired result with this query:

db.codes.aggregate( [
  { $project: { code: { $eq: [ '$code', 1 ] } } },
  { $facet: {
     code_is_1: [
          { $match: { code: true } },
          { $count: "Code equals 1" },
     ],
     code_not_1: [
          { $match: { code: false } },
          { $count: "Code not equals 1" },
     ],
  } },
  { $project: { Counts: { $concatArrays: [ "$code_is_1", "$code_not_1" ] } } },
] )

The result will look like this with the test documents you posted: { "Counts" : [ { "Code equals 1" : 2 }, { "Code not equals 1" : 2 } ] }

Upvotes: 0

Tunmise Ogunniyi
Tunmise Ogunniyi

Reputation: 2573

You can conditionally sum the counter.

aggregate([
    {
      $group: {
        _id: null,
        key1: { // Count of all documents with keys(code) that are equal to 1
          '$sum': {
            '$cond': {
              if: { '$eq': [1, '$code'] },
              then: 1,
              else: 0
            }
          }
        },
        otherKeys: { // Count of all other documents with keys not equal to 1
          '$sum': {
            '$cond': {
              if: { '$eq': [1, '$code'] },
              then: 0,
              else: 1
            }
          }
        }
      },
    }
  ])

This would output a result document like this:

{ "_id" : null, "key1" : *, "otherKeys" : * }

Where key1 is the count of all documents with keys equal to 1, while otherKeys is the count of all documents with keys not equal to 1.

Upvotes: 1

Related Questions