SamuraiJack
SamuraiJack

Reputation: 5539

MongoDb Aggregation - How to get $count along with other properties?

MobgoDb Playground

Attempt 1: (this returned only the total )

 db.collection.aggregate([
  {
    $match: {
      "dob.age": 59
    }
  },
  {
    $count: "total"
  },
  {
    $project: {
      "dob.age": 1,
      "total":1
    }
  }
])

Attempt 2 (Exception -A pipeline stage specification object must contain exactly one field)

db.collection.aggregate([
  {
    $match: {
      "dob.age": 59
    }
  },
  {
    $count: "total",
    "dob.age": 1
  } 
])

Attempt 3 (empty object):

db.collection.aggregate([
  {
    $match: {
      "dob.age": 59
    }
  },
  {
    $group: {
      _id: null,
      total: {
        $sum: 1
      }
    }
  },
  {
    $project: {
      _id: 0,
      "dob.age": 1
    }
  }
])

Upvotes: 0

Views: 1563

Answers (3)

Shubham Verma
Shubham Verma

Reputation: 9933

As you didn't mention that you want to count on cloud.mongodb.com (cloud mongo), I would like to add that part also. In cloud mongo you add the following query to get the count:

Stage 1: $match:

    /**
     * Query: The query in MQL.
     */
    {
      "YOUR_KEY":"YOUR_VALUE_FOR_FETCH"
    }

Stage 2: $count:

/**
 * Provide the field name for the count.
 */
'total'

Example:

screenshot of cloud mongo:

enter image description here

Upvotes: 0

Manuel Spigolon
Manuel Spigolon

Reputation: 12880

If you run match:"dob.age": 59 the output age will be a constant 59.

In any case, you need to run the group by so you will have the total of rows by age:

db.collection.aggregate([
  {
    $match: {
      "dob.age": 59
    }
  },
  {
    $group: {
      _id: "$dob.age",
      total: {
        $sum: 1
      }
    }
  },
  {
    $project: {
      _id: 0,
      age: "$_id",
      "total": 1
    }
  }
])

otherwise I would suggest to run simply:

db.collection.count({"dob.age": 59}) // it will be 2 as well

Upvotes: 0

Gibbs
Gibbs

Reputation: 22964

You can do this - have equivalent to $count

play

db.collection.aggregate([
  {
    $match: { //match condition
      "dob.age": 59
    }
  },
  {
    $group: {//$count equivalent
      _id: null,
      myCount: {
        $sum: 1
      },
      "data": {//all other fields
        $push: "$$ROOT"
      }
    }
  },
  {
    $project: {//removing null id - you can skip this if null id is not a problem
      _id: 0
    }
  }
])

Upvotes: 1

Related Questions