1

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 !

1 Answer 1

2

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
            }
        }
    }
])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.