简体   繁体   English

MongoDB 查找查询在 200MB 以上的数据库上花费太多时间

[英]MongoDB find query takes too much time on a database of 200MB+

In my database there is a createdAt column.在我的数据库中有一个 createdAt 列。 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);
    })
}

in your query, you can do some things that might be helpful for you like在您的查询中,您可以做一些可能对您有帮助的事情

  1. you can create an index on your collection.您可以为您的收藏创建索引。
  2. if you using sorting on createdAt as 1 then might be you not need to sort your data.because it's already sorted.如果您在createdAt上使用排序为 1,那么您可能不需要对数据进行排序。因为它已经排序了。
  3. you can use projection in your query to remove unnecessary data(which is not required) in the result.您可以在查询中使用投影来删除结果中不必要的数据(不需要)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM