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

Aggregate function isn't showing results with a count greater than 1

I’m running this aggregate function, which is supposed to only show results when they have a count greater than 1. When I remove ‘count’: { ‘$gt’: 1 } the aggregate works, however it obviously shows all results. How should I use this count correctly?

db.getCollection('songs').aggregate([
{
  '$match': { 'is_song': 1, 'is_soundtrack': 0, 'count': { '$gt': 1 } }
},
{
  '$group': { '_id': { 'name': '$name', 'artist_id': '$artist_id' }, 'count': { '$sum': 1 } }        
},
{ 
   '$sort': { 'count': -1 }
}
])

sample data:

{
"_id" : ObjectId("5f93a43b4e8883298849ad18"),
"name" : "Come Fly With Me",
"song_id" : 5,
"artist_id" : 5,
"is_song" : 1,
"is_soundtrack" : 0,
"updatedAt" : ISODate("2016-10-04T13:34:53.328Z")
}

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 :

You should not add 'count': { '$gt': 1 } in the first $match stage.

As the count field is only populated after the $group stage.

So, you need add another $match stage after $group stage for filtering document with the count value is greater than 1.

db.collection.aggregate([
  {
    "$match": {
      "is_song": 1,
      "is_soundtrack": 0
    }
  },
  {
    "$group": {
      "_id": {
        "name": "$name",
        "artist_id": "$artist_id"
      },
      "count": {
        "$sum": 1
      }
    }
  },
  {
    $match: {
      "count": {
        "$gt": 1
      }
    }
  },
  {
    "$sort": {
      "count": -1
    }
  }
])

Sample Mongo Playground

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