I am having performance issues on the API I am developing using NodeJS+Express+MongoDB.
On running the aggregate with $match on particular product, the performance is good but for a open search it's really slow.
I want to run a group on two columns: country and exporter and then fetch the result limited to 3 results per group on country.
Requirement: Total Count of unique exporters from each country along with any 3 records from each country.
On running explain() on my aggregate function I am getting the following key pointers that flag about my queries being slow. Please correct me if I am wrong.
"indexFilterSet": false"winningPlan": {"stage": "COLLSCAN","direction": "forward"},
Ran the query on 9,264,947 records and time taken is about 32 seconds.
I have tried using compound index as well as single field index but it's not helping at all, as I feel the index is not being used with $match being empty {}
Below is the query I am running on mongoDB using mongoose driver
Model.aggregate([
{"$match" : query},
{ $group : {_id: {country: "$Country", exporter: "$Exporter"}, id: {$first: "$_id"}, product: { $first: "$Description" }}},
{ $group : {_id: "$_id.country", data: {$push: { id: "$id", company: "$_id.exporter", product: "$product" }}, count:{$sum:1}}},
{ "$sort": { "count": -1 } },
{
$project: {
"data": { "$slice": [ "$data", 3 ] },
"_id": 1,
"count": 1
}
},
]).allowDiskUse(true).explain()
where, query is dynamically build and is by default empty {} for a collection-wide search.
Indexed fields are
Compound Index:
{Country: 1, Exporter: 1}Text Index:
{Description: "text"}
Full explain() response:
{
"success": "Successfull",
"status": 200,
"data": {
"stages": [
{
"$cursor": {
"query": {},
"fields": {
"Country": 1,
"Description": 1,
"Exporter": 1,
"_id": 1
},
"queryPlanner": {
"plannerVersion": 1,
"namespace": "db.OpenExportData",
"indexFilterSet": false,
"parsedQuery": {},
"winningPlan": {
"stage": "COLLSCAN",
"direction": "forward"
},
"rejectedPlans": []
}
}
},
{
"$group": {
"_id": {
"country": "$Country",
"exporter": "$Exporter"
},
"id": {
"$first": "$_id"
},
"product": {
"$first": "$Description"
}
}
},
{
"$group": {
"_id": "$_id.country",
"data": {
"$push": {
"id": "$id",
"company": "$_id.exporter",
"product": "$product"
}
},
"count": {
"$sum": {
"$const": 1
}
}
}
},
{
"$sort": {
"sortKey": {
"count": -1
}
}
},
{
"$project": {
"_id": true,
"count": true,
"data": {
"$slice": [
"$data",
{
"$const": 3
}
]
}
}
}
],
"ok": 1
}
}
Collection Size : 9,264,947 records & 10.2 GB
Response Time : 32154 ms
The query is getting slower as the size of my collection is increasing.