Getting MongoDB to use an index in aggregation pipeline

Hi, I have a collection of about 45k documents on which I want to perform an aggregation. Each document looks like this:

{
    _id: ObjectId("..."),
    Name: '...',
    'Claimed For': null,
    Game: { rowId: '62808688723f058679961078', display: 'DTHG' },
    Region: { rowId: '6264884a4d3c698967514d79', display: 'Global' },
    Platform: { rowId: '6264886e4d3c698967514d7c', display: 'Steam (PC)' },
    'Claimed TimeStamp': null,
    Category: null,
    Claimed: false,
    'Claimed By': null,
    Notes: null
  }

I am running this aggregation pipeline on it:
db.coll.aggregate([{ "$group": { "_id": "$Game.rowId", "Game": { "$first": "$Game" }, "COUNT": { "$count": {} }}}])
I have an index on “Game.rowId”. However, I cannot seem to get Mongo to use the index when running the aggregation, unless I only do "$group": { "_id": "$Game.rowId", "Game": { "$first": "$Game" }} without the count, which is not very useful.

I am getting Profiler warning emails from MongoDB basically every time I run this query, but I don’t know how to make it use the index. Any help would be appreciated.

Thanks!
Bruno.

Try to $sort on Game.rowId first.

It worked! Thanks for your help.

1 Like