LastRide
LastRide

Reputation: 85

MongoDB aggregation with many embedded documents

I have next structure of my mongoDB collection:

{
  "_id": "1",
  "sessions": [
    {
      "type": "default",
      "pageViews": [
        {
          "path": "/",
          "host": "example.com",
          "events": [
            {
              "name": "event1"
            },
            {
              "name": "event1"
            }
          ]
        }
      ]
    },
    {
      "type": "default",
      "pageViews": [
        {
          "path": "/",
          "host": "example.com",
          "events": [
            {
              "name": "event1"
            },
            {
              "name": "event1"
            }
          ]
        }
      ]
    }
  ]
}

I need to get count of sessions, pageViews and events in one query grouping by _id field.

I do:

db.collection.aggregate([

    {
        $unwind: "$sessions"
    },

    {
        $unwind: "$sessions.pageViews"
    },

    {
        $group: {
            _id : "$_id",
            totalEvents: {
                $sum: {
                    $size: "$sessions.pageViews.events"
                },
            },
            totalPageViews: {
                $sum: 1
            }
        }
    }

])

But I can't understand how to get count of sessions.

How can I get count of sessions in this query ?

Thanks !

Upvotes: 1

Views: 1063

Answers (1)

CodeMan
CodeMan

Reputation: 1405

Try counting the sessions before unwinding using $project (available in mongodb 3.2). Then the total sessions will be available in the $group stage. You can just take the $first totalSessions for each _id as all records with the same _id will have the same number of sessions:

db.collection.aggregate([

    { $project : { sessions: 1, totalSessions : { $size : "$sessions" } } },

    {
        $unwind: "$sessions"
    },

    {
        $unwind: "$sessions.pageViews"
    },

    {
        $group: {
            _id : "$_id",
            totalSessions: { $first : "$totalSessions" },
            totalEvents: {
                $sum: {
                    $size: "$sessions.pageViews.events"
                },
            },
            totalPageViews: {
                $sum: 1
            }
        }
    }
])

Upvotes: 2

Related Questions