Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

MongoDB – Group and Find Top N with condition

Consider this test collection, in which an airport is identified by AirportID:

{ AirportID:"1001", delayMinutes :"15.0" },
{ AirportID:"1004", delayMinutes :"3.0" },
{ AirportID:"1001", delayMinutes :"20.0" },
{ AirportID:"1002", delayMinutes :"6.0" },
{ AirportID:"1002", delayMinutes :"25.0" },
{ AirportID:"1004", delayMinutes :"55.0" },

I want to group it together and list the top 2 from that list with the condition that $delayMinutes is greater than "10.0".
I want to group it together and list the top 2 from that list.
Code I have tried

db.test.aggregate([
  {
    $group: {
      _id: "$AirportID",
      delayMinutes: {
        $sum: {
          "$toDouble": "$delayMinutes"
        }
      }
    }
  },
  {
    $sort: {
      delayMinutes: -1
    }
  },
  {
    $limit: 2
  }
])

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

As the requirement is clarified,

You need to filter the document first with delayMinutes field greater than ($gt) 10.

Make sure you convert the delayMinutes to double before comparing.

db.collection.aggregate([
  {
    $match: {
      $expr: {
        $gt: [
          {
            "$toDouble": "$delayMinutes"
          },
          10
        ]
      }
    }
  },
  {
    $group: {
      _id: "$AirportID",
      delayMinutes: {
        $sum: {
          "$toDouble": "$delayMinutes"
        }
      }
    }
  },
  {
    $sort: {
      delayMinutes: -1
    }
  },
  {
    $limit: 2
  }
])

Sample Mongo Playground


And you can update the delayMinutes field to double with the $set stage. As it is redundant in the $match and $group stages.

db.collection.aggregate([
  {
    $set: {
      delayMinutes: {
        "$toDouble": "$delayMinutes"
      }
    }
  },
  {
    $match: {
      $expr: {
        $gt: [
          "$delayMinutes",
          10
        ]
      }
    }
  },
  {
    $group: {
      _id: "$AirportID",
      delayMinutes: {
        $sum: "$delayMinutes"
      }
    }
  },
  {
    $sort: {
      delayMinutes: -1
    }
  },
  {
    $limit: 2
  }
])

Sample Mongo Playground (with $set)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading