Showing posts with label aggregation. Show all posts
Showing posts with label aggregation. Show all posts

Friday, 29 January 2016

How to find count of multiple fields in MongoDb

Problem Statement:
I have a use case where i need to find the count of activity done on JobId.
I have a mongodb collection jobslog which has following data

jobId,action
1 a (apply)
2       v (view)
3      a (apply)
1 v (view)

I knew the query in mysql
select count(a),count(v) from jobslog group by jobId

But I do not know how to do it in Mongo.So i did lots of search on google for that.

Solution:
Query In MongoDB
db.jobslog.aggregate([
                    { $group: {
                        _id: "$jobId",
                         view_count: { $sum: {
                                        $cond: [ { $eq: [ '$a', 'v' ] }, 1, 0 ]
                                     } },
                         apply_count: { $sum: {
                                        $cond: [ { $eq: [ '$a', 'a' ] }, 1, 0 ]
                                     } },
                     }},
                     { $out : output_collection_name }

])