I've created a collection where all documents have the same schema, like this:
{
"_id" : "8ded8078-4f0f-41e4-87aa-5e4d3227392d",
"AreaId" : "b321ddef-8cdd-4b80-9edf-07558e6a2cac",
"InvoiceNumber" : "0002115545654",
"CreatedAt" : "2021-07-07T12:38:00.000Z",
"CreatedBy" : "Juliano Oliveira",
"InvoicePeriodStart" : "2021-07-16T00:00:00.000Z",
"InvoicePeriodEnd" : "2024-07-16T00:00:00.000Z",
"Products" : [
{
"Section" : NumberInt(1),
"ProductId" : "434fe51f-ac59-4708-9177-a7742f54e282",
"ProductNumber" : "004846846684",
"Name" : "Some random product A",
}
],
"Amount" : 2732.49,
"CustomerId": 8ded8078-4f0f-41e4-87aa-5e4d3227392d,
"CustomerName": "Some Random Company",
"CustomerEmailAddress": "******@randomcompany.com"
}
I've created some single field indexes for the following fields:
- AreaId
- InvoiceNumber
- CreatedAt
- CreatedBy
- InvoicePeriodStart
- InvoicePeriodEnd
- Products.Section
- Products.ProductId
- Products.Name
The collection has only 500k documents and the queries are generated by a query builder using MongoClient in a C# service, with pagination. After some changes, the query builder generates this query:
{
"Products": {
"$elemMatch": { "Section": 1, "ProductId": "298d6420-0f92-48f0-be1c-093f73f4f012" } }
}
Running an explain on this query and comparing with the query bellow:
{ "Products.Role": 1, "Products.ProductId": "298d6420-0f92-48f0-be1c-093f73f4f012" }
they show different runtimeExecutionTimes as you can see below:
Version with $elemMatch
"runtimeExecutionTimes" : {
"queryEngineExecutionTimeMS" : 72.0501,
"systemFunctionExecutionTimeMS" : 22.13,
"userDefinedFunctionExecutionTimeMS" : 0
},
Version without
"runtimeExecutionTimes" : {
"queryEngineExecutionTimeMS" : 53.11,
"systemFunctionExecutionTimeMS" : 32.2899,
"userDefinedFunctionExecutionTimeMS" : 0
},
Why is this different? One thing that I've noticed is that the version using $elemMatch requires an index for Products array and the version without it, requires an individual index for each field inside the Products array (like Products.ProductId, Products.Section).
How can I optimize it and run the CountDocuments faster?