Aggregation and Find Operator

42 views
Skip to first unread message

Tamil Arasi

unread,
Mar 12, 2016, 5:08:22 AM3/12/16
to mongodb-user
Hi i have an use case where i have find all the matching records and apply the aggregation like count ,sum , group by etc . Can i use such scanerios where i have to use find and aggregate function together or should i find then get the cursor object and have to perform aggregation operation separetely 

Alan Reyes

unread,
Mar 12, 2016, 8:15:30 PM3/12/16
to mongodb-user
You can use the $match stage of the aggregation pipeline as a find, then a $group stage to apply your aggregation operation.

Wan Bachtiar

unread,
Mar 13, 2016, 6:40:48 PM3/13/16
to mongodb-user

Hi Tamil,

As mentioned by Alan, you can use $match pipeline operator to filter documents.

For example, the following selects documents to process, then pipes the results to the $group pipeline operator to generate count.

db.collection.aggregate( [
  { $match: { $or: [ { score: { $gt: 70, $lt: 90 } }, { views: { $gte: 1000 } } ] } },
  { $group: { _id: null, count: { $sum: 1 } } }
] );

See Aggregation pipeline operators for a list of available operators in MongoDB v3.2.

Also worth mentioning:

  • Place the $match as early in the pipeline as possible, because $match limits the total number of documents in the pipeline and minimize the amount of processing down the pipe.
  • If you place a $match at the very beginning of the pipeline, the query can take advantage of indexes.

If you still have any questions, can you provide the following:

  • MongoDB version that you are using.
  • Example documents.
  • Example results that you are after.
  • Aggregation pipeline that you have tried so far.

Regards,

Wan.

Tamil Arasi

unread,
Mar 14, 2016, 1:36:47 AM3/14/16
to mongodb-user
I guess Match is equivalent to HAVING clause in Postgres But i want something like Select city,count(*) from Employee where division = 'Chennai' GROUP BY city.
Iam using Mongo DB version 3.2 . 

Virendra Agarwal

unread,
Mar 14, 2016, 1:44:43 AM3/14/16
to mongodb-user
Hi Tamil,

Aggergation framework does the same job you are asking.
$ Match operation is equivalent to find
$ Project is equivalent to select field operation
$ Group is group by.
And aggrgation comes with all $sum / $avg etc.

Regards
Virendra Agarwal

Alan Reyes

unread,
Mar 14, 2016, 1:50:36 PM3/14/16
to mongodb-user
Try with:

db.Employee.aggregate(
[
 
{"$match": { "division": "Chennai" } },
 
{"$group": { "_id": "$city", "count": {"$sum": 1} } }
]
)

$match filters only Employee in division "Chennai", then the resulting dataset is grouped by city, and for each grouped document the "count" attriobute of the result is increased by 1.
Reply all
Reply to author
Forward
0 new messages