'MongoDB find query takes too much time on a database of 200MB+
In my database there is a createdAt column. What I am trying to do is fetch all the data of a specific month given a current month and year. What would be the most fastest and efficient way to do it?
This is my code:
module.exports.fetchVotings = (year, month) => {
return new Promise(async (resolve, reject) => {
const days_count = new Date(year, month, 0).getDate();
console.log(days_count);
// get data of a month of the given year of createdAt
let res = await mongoose.connection.db.collection('votings').find({
"createdAt": {
"$gte": new Date(year, month - 1, 1),
"$lt": new Date(year, month, days_count)
}
}).sort({ createdAt: 1 }).toArray();
resolve(res);
})
}
Solution 1:[1]
in your query, you can do some things that might be helpful for you like
- you can create an index on your collection.
- if you using sorting on createdAt as 1 then might be you not need to sort your data.because it's already sorted.
- you can use projection in your query to remove unnecessary data(which is not required) in the result.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | RONAK SUTARIYA |
