I am working on a Golang project (db MongoDB). I have executed the below query but it is taking too much time to load the data. In this, I am getting data from 2 collections with multiple stages.
db.getCollection('Collection1').aggregate([
{
"$lookup": {
"localField": "uid",
"from": "collection2",
"foreignField": "_id",
"as": "user_info"
}
},
{
"$unwind": "$user_info"
},
{
"$lookup": {
"localField": "cid",
"from": "collection3",
"foreignField": "_id",
"as": "cust_info"
}
},
{
"$lookup": {
"from": "logs",
"let": {"id": "$_id"},
"pipeline": [
{"$match": {"$expr": {"$eq": ["$$id", "$log_id"]}}},
{"$sort": {"log_type": 1}}],
"as": "logs_data"
}
},
{
"$sort": {"logs_data.logged_on":-1}
},
{
"$skip": 1
},
{
"$limit": 2
},
])
My requirement is to add 2 time sort within the same query:
- Within the logs array
"$sort": {"log_type": 1}} - For the end result
"$sort": {"logs_data.logged_on":-1}
For this I have tries the following indexes:
{"logged_on" : -1}
{"log_id":1, "log_type":1}
But the query taking still 6-7 sec to execute.
If I remove "$sort": {"logs_data.logged_on":-1} then it works fast but with this sorting it is taking too much time.
how and what can I do to improve the response time.
logscollection contain any documents that don't match an_idfromcollection1?