Hi,
I have a fairly simple use case but I am struggling to get it to work as I’d like.
Collections:
Cases:
-_id
-Description
… more fields
Items:
-_id
-Description
-CurrentOfficeName
…more fields
Now, we used to have a array field in Cases called ‘items’ that stores the id’s of the items that belong to that particular case as an unbounded array. That has worked up until now, but we’d like to change the system so a case can have over 100k items. So I created a join table to handle that:
CaseItems:
-_id
-CaseId
-ItemId
-OrganizationId
So now, we’re using $lookup to retrieve all items that belong to a case like so:
db.getCollection('caseItems').aggregate([
{
"$match":{
"CaseId":NumberLong(3067920),
"OrganizationId":NumberLong(1)
}
},
{
"$lookup":{
"from":"items",
"localField":"ItemId",
"foreignField":"_id",
"as":"result"
}
},
{
"$replaceRoot":{
"newRoot":{
"$mergeObjects":[
"$$ROOT",
{
"$arrayElemAt":[
"$result",
0
]
}
]
}
}
},
{
"$sort":{
"CurrentOfficeName":-1
}
},
{
"$skip":0
},
{
"$limit":1000
}
])
The issue I’m having is that the $sort field makes the query take 15+ seconds (The sort field on the items collection is an index). If I remove the sort field then the query is very fast.
So, my question is: Can Mongo db handle this? If so, then what am I doing incorrectly?
Thanks for all the help!
AJ