Home > Software design >  Aggregate function isn't showing results with a count greater than 1
Aggregate function isn't showing results with a count greater than 1

Time:01-20

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")
}

CodePudding user response:

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

  •  Tags:  
  • Related