Hi All, I am Emmanuel Katto. I’m working on a project that involves storing and querying a large collection of documents in MongoDB. The collection contains around 10 million documents, and I’m struggling to query it efficiently when using complex conditions.
I have a document structure that looks like this:
{
“_id”: ObjectId,
“name”: String,
“categories”: [String],
“tags”: [String],
“createdAt”: Date,
“updatedAt”: Date
}
I need to query this collection to retrieve all documents that match the following conditions:
- The
namefield contains the string “example” - The
categoriesarray contains at least one element that matches “categoryA” or “categoryB” - The
tagsarray contains at least one element that matches “tag1” or “tag2” - The
createdAtfield is within a specific date range (e.g. last 24 hours)
I’ve tried using the $regex operator to query the name field, and the $elemMatch operator to query the categories and tags arrays. However, my queries are taking a long time to execute and returning a large number of results.
Is there a more efficient way to query my collection using MongoDB’s aggregation pipeline? Please let me know.
Thanks!
Emmanuel