Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

314
Views
Is it possible to aggregate $$ROOT in mongo db?

I have following Mongo Collection.

[
  {
    "query": "a",
    "page": "p1",
    "clicks": 10,
    "date": "x"
  },
  {
    "query": "b",
    "page": "p1",
    "clicks": 5,
    "date": "x"
  },
  {
    "query": "a",
    "page": "p1",
    "clicks": 5,
    "date": "y"
  },
  {
    "query": "c",
    "page": "p2",
    "clicks": 2,
    "date": "y"
  },
  
]

Output Should be like this :

 [
      {
        "page" : "p1",
        "most_clicks_query" : "a",
        "sum_of_clicks_for_query" : 15

      },
{
        "page" : "p2",
        "most_clicks_query" : "c",
        "sum_of_clicks_for_query" : 2

      },
  
      
    ]

Logic to get this Output :

I need the query name that has most clicks for each page with sum of clicks (for that query)

What I ask :

  • I am hoping to get this result in one aggregation query.
  • So I am playing with $$ROOT.
  • In this path, now I am stuck with grouping the $$ROOT (to get sum of clicks for queries).
  • Can someone guide me a better path to do this?
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Here is the aggregation you're looking for:

db.collection.aggregate([
  {
    "$group": {
      "_id": {
        "page": "$page",
        "query": "$query"
      },
      "sum_of_clicks_for_query": {
        "$sum": "$clicks"
      }
    }
  },
  {
    "$project": {
      "_id": false,
      "page": "$_id.page",
      "most_clicks_query": "$_id.query",
      "sum_of_clicks_for_query": true
    }
  },
  {
    $sort: {
      "sum_of_clicks_for_query": -1
    }
  },
  {
    $group: {
      _id: "$page",
      group: {
        $first: "$$ROOT"
      }
    }
  },
  {
    $replaceRoot: {
      newRoot: "$group"
    }
  }
])

Playground: https://mongoplayground.net/p/Uzk3CuSwVRM

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!