Amar
Amar

Reputation: 63

Mongo aggregate query $sort before $group taking a lot of time

I need some data for a user sorted by time and grouped by the phone numbers. Used $match followed by $sort and then $group. The query is talking a lot of time on mongo. If i remove any one of the $sort or $group criteria the query executes within milli secs.

the query i am using is

db.buyerResponse.aggregate([
    { $match: { superProfileId: 321956, responseDate: { $gte: new Date(1432739021103), $lt: new Date(1448636621103) } } }, 
    { $sort: { responseDate: -1 } },
    { $group: { _id: "$phone", responseId: { $first: "$_id" } }}, { $skip: 0 }, 
    { $limit: 50 }
])

Upvotes: 3

Views: 1454

Answers (1)

Assaf Lavie
Assaf Lavie

Reputation: 75983

You should group before sorting. Once you group, there are a lot less records to sort. Generally, you almost always want to sort last.

Upvotes: 2

Related Questions