Hi Ivan,
Actually the database executed the query pretty quick, in about 3ms, so I think it’s your network roundtrip that’s inflating the query response time:
"executionStats" : {
"executionSuccess" : true,
"nReturned" : 112,
"executionTimeMillis" : 3,
"totalKeysExamined" : 453,
"totalDocsExamined" : 262,
This is also in line with your observation that sometimes it returns in 150ms, other times in 250ms. Typically a database query would be more consistent.
However there are some improvements that can be made on the query side. I believe this is the query:
{ID: {$in: [...]}, post_status: 'publish', post_type: 'product', 'media.featured_image': {$exists: true}
So there’s a couple of things I noticed on the query execution:
-
From the explain output, it returned 112 documents, examined 453 index keys and 262 documents. That means that it needs to scan ~2x the documents, and ~4x the index keys to return the relevant 112 documents. Ideally, you want the same number on all three of them, meaning the server doesn’t spend any time looking at irrelevant documents/index keys.
-
I noticed that the query only used the index on the field ID
. To back this query properly, you should have a compound index on all the involved fields. Something like db.collection.createIndex({ID:1, post_status:1, post_type:1, 'media.featured_image':1})
. See Create Indexes to Support Your Queries for more information.
Regarding point (1) above, it’s a bit hard to achieve with your current query since you have an $exists: true
clause. Typically this clause would force MongoDB to load the document from disk to determine if the field is there or not. This can’t really be helped by indexes, since by its nature indexes store what’s in a document, and not what doesn’t exist in a document. To fully solve point (1) then would need a bit of a rethink on how the query and the documents should be structured.
If you’re interested in an in-depth tutorial on data modeling, you might be interested in the free course M320: Data Modeling from MongoDB University.
Best regards,
Kevin