Such difference in speed may be because aggregation with $searchMeta strongly relies on underlying indexes, while the other aggregation based on $match + $group stages, that I provided above - not. What indexes you have on your collection? You can check it with db.collection.getIndexes() method.
To make the aggregation above faster, you should create a compound index, that would include:
- A field, that you will use to sort documents (in your case it is
last_message_datetime, that you use to select document withing a date range). Since you need to get only some latest set of documents (for the last hour), you need to make your index descendant-1. - Fields, that are used to filter out unnecessary documents (in the example your provided those fields are:
st,aff,src).
Example of a compound index definition (relies on the example dataset I provided initially):
db.messages.createIndex({
createdAt: -1, // for sorting
channelId: 1 // for filtering
});
Try this out and let me know, if it helped ![]()