Friday, 26 January 2018

Mongo DB Aggregate Functions , Queries and Joins


To get the total no of records created by user in each category

db.tablename.aggregate(

    [



        {

            $group: {

                _id : { project : "$project" , user : '$user' },  total : {$sum : 1 }

            }

        },


    ]


);


Query for all Documents in a collection

db.restaurants.find()

Aggregate Function having Match and Group clauses

db. tablename.aggregate(

               // Pipeline
               [
                              // Stage 1
                              {
                                             $match: {
                                             "lastRunDate" : {"$gte" : ISODate("2017-01-01T00:00:00.000+0000"),"$lte" : ISODate("2017-01-14T23:59:59.999+0000")}
                                             }
                              },

                              // Stage 2
                              {
                                             $group: {
                                             _id : '$project' , total : { $sum : 1}
                                             }
                              },

               ]

);

Note: Date format is 2017-01-14 (YYYY-MM-DD)


Joins using Mongo Db

db.tablename.aggregate(

               // Pipeline
               [
                              // Stage 1
                              {
                                             $lookup: {
                                                from: <collection to join>,
                                                localField: <field from the input documents>,
                                                foreignField: <field from the documents of the "from" collection>,
                                                as: <output array field>
                                             }
                              },

                              // Stage 2
                              {
                                             $match: {
                                             "date": { $gte: ISODate("2017-01-01") , $lte:ISODate("2017-01-14") }
                                             }
                              },

                              // Stage 3
                              {
                                             $project: {
                                              'data.user' : '$data.user', 'result' : '$result' ,'name' :'$name' , 'project' : '$project' , 'data.name' : '$data.name'
                                             }
                              },
               ],

               // Options
               {
                              cursor: {
                                             batchSize: 50
                              }
               }

);

0 comments:

Post a Comment