How can i count total documents and also grouped counts simultanously in mongodb aggregation?

Fahad Hassan

I have a dataset in mongodb collection named visitorsSession like

{ip : 192.2.1.1,country : 'US', type : 'Visitors',date : '2019-12-15T00:00:00.359Z'},
{ip : 192.3.1.8,country : 'UK', type : 'Visitors',date : '2019-12-15T00:00:00.359Z'},
{ip : 192.5.1.4,country : 'UK', type : 'Visitors',date : '2019-12-15T00:00:00.359Z'},
{ip : 192.8.1.7,country : 'US', type : 'Visitors',date : '2019-12-15T00:00:00.359Z'},
{ip : 192.1.1.3,country : 'US', type : 'Visitors',date : '2019-12-15T00:00:00.359Z'}

I am using this mongodb aggregation

[{$match: {
  nsp : "/hrm.sbtjapan.com",
  creationDate : {
  $gte: "2019-12-15T00:00:00.359Z",
  $lte: "2019-12-20T23:00:00.359Z"
 },
 type : "Visitors"
 }}, {$group: {
 _id : "$country",
 totalSessions : {
   $sum: 1
  }

  }}, {$project: {
    _id : 0,
    country : "$_id",
    totalSessions : 1
   }}, {$sort: {
  country: -1
 }}]

using above aggregation i am getting results like this

[{country : 'US',totalSessions  : 3},{country : 'UK',totalSessions  : 2}]

But i also total visitors also along with result like totalVisitors : 5 How can i do this in mongodb aggregation ?

prasad_

You can use $facet aggregation stage to calculate total visitors as well as visitors by country in a single pass:

db.visitorsSession.aggregate( [
  {
      $match: {
          nsp : "/hrm.sbtjapan.com",
          creationDate : {
              $gte: "2019-12-15T00:00:00.359Z",
              $lte: "2019-12-20T23:00:00.359Z"
          },
          type : "Visitors"
      }
  },
  { 
      $facet: {
            totalVisitors: [
                { 
                    $count: "count" 
                }
            ],
            countrySessions: [
                {
                    $group: {
                        _id : "$country", 
                        sessions : { $sum: 1 }
                    }
                },
                { 
                    $project: { 
                        country: "$_id", 
                        _id: 0, 
                        sessions: 1 
                    } 
                }
            ],
      }
  },
 { 
      $addFields: { 
          totalVisitors: { $arrayElemAt: [ "$totalVisitors.count" , 0 ] },
      } 
  }
] )

The output:

{
        "totalVisitors" : 5,
        "countrySessions" : [
                {
                        "sessions" : 2,
                        "country" : "UK"
                },
                {
                        "sessions" : 3,
                        "country" : "US"
                }
        ]
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How can I group documents by object in mongodb aggregation?

How to count the total documents in phalcon mongodb collection

How can I count the documents in an array depending on their value in mongodb?

How I can count documents in collection MongoDB Java

MongoDB - Aggregation Framework (Total Count)

Can I get counts for different field values in a MongoDB aggregation pipeline?

Total objects doesnot match with sum of individual document collection counts in mongodb, the collections count is also mismatch

In Mongodb aggregation, how can I return all documents containing an array value whose second element exists?

How to group documents and get the count of documents and also get Avg of sub-documents in mongoDB

MongoDB Aggregation: How can I apply pagination in MongoDB aggregation

How can I find the total number of user generated documents within a mongodb database?

How can we retain only unique documents in mongodb aggregation

Count number of documents using Aggregation MongoDB

How to total Count in mongoDB?

How can I decrease unwind stages in aggregation pipeline for nested documents?

Getting count of total documents when using aggregation along with skip and limit

How can I find similar documents in MongoDB?

How can I search for the embedded documents in mongodb?

How can I transpose a list of documents in MongoDB?

How can I aggregate MongoDB documents by minute?

MongoDB: How can I calculate total count without using $group operator

How do i count number of referals using aggregation in mongoDB

How can I count values that can be grouped by another columns in R

Total count and field count with condition in a single MongoDB aggregation pipeline

How to count specific documents in a row using aggregation?

How to group and count with MongoDB aggregation

How to count fields in Mongodb Aggregation

How to add the results of a group, to the grouped documents? MongoDB

How to paginate aggregation query results in MongoDB and get a total document count (Node.js + Mongoose)?