【问题标题】:MondoDB/Mongoose query responce is too slowMongoDB/Mongoose 查询响应太慢
【发布时间】:2020-06-25 04:31:13
【问题描述】:

我是 MongoDB/Mongoose 的新手,并且使用过一个非常大的数据库(超过 25000 个文档)。我需要配置不同的查询:按字段,前 10 个文档,一个按 id。问题在于性能 - 服务器响应太慢(大约 10-15 秒)。 请告诉我如何配置它以使服务器响应快速? 它是仅依赖于模式设置,还是还可以依赖于其他东西,例如数据库连接参数或查询参数? 附言查询应按“地区”和“地区”。 感谢您的帮助!

这是架构:

const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const houseSchema = new Schema({
  code: {
    type: String,
    required: false
  },
  name: {
    type: String,
    required: true
  },
  district: {
    type: String,
    required: true
  },
  locality: {
    type: String,
    required: false
  },
  recountDate: {
    type: Date,
    default: Date.now
  },
  eventDate: {
    type: Date,
    default: Date.now
  },
  events: {
    type: Array,
    default: []
  }
});

module.exports = mongoose.model('House', houseSchema);

连接参数:

mongoose.connect(
  `mongodb+srv://${process.env.MONGO_USER}:${process.env.MONGO_PASSWORD}@cluster0-vuauc.mongodb.net/${process.env.MONGO_DB}?retryWrites=true&w=majority`,
  {
    useNewUrlParser: true,
    useUnifiedTopology: true
  }
).then(() => {
  console.log('Connection to database established...')
  app.listen(5555);
}).catch(err => {
  console.log(err);
});

使用 Relay 执行查询:

query {
  viewer {
    allPosts (first: 10) {
      edges {
        node {
          id
          code
          district
          locality
          recountDate
          eventDate
          events
        }
      }
    }
  }
}

【问题讨论】:

    标签: javascript node.js mongodb express mongoose


    【解决方案1】:

    使用预测只返回必要的数据 当您只需要文档中的一部分字段时,您可以通过仅返回您需要的字段来获得更好的性能:

    例如,如果在您对帖子集合的查询中,您只需要时间戳、标题、作者和摘要字段,您将发出以下命令:

    db.posts.find( {}, { timestamp : 1 , title : 1 , author : 1 , abstract : 1} ).sort( { timestamp : -1 } ).limit(10)
    

    您可以阅读查询优化here

    【讨论】:

      【解决方案2】:

      确保不是连接问题。尝试从 MongoDB shell 运行您的查询

      mongo mongodb+srv://${process.env.MONGO_USER}:${process.env.MONGO_PASSWORD}@cluster0-vuauc.mongodb.net/${process.env.MONGO_DB}?retryWrites=true&w=majority
      db.collection.find({condition}).limit(10)
      

      如果在 MongoDB shell 中它的响应速度比 Mongoose 快

      Node.js 驱动程序存在问题,它使用纯 Javascript BSON serializer,从 BSON 序列化到 JSON 非常慢。

      尝试安装bson-ext

      bson-ext 模块是另一种 BSON 解析器,用 C++ 编写。它提供了更好的反序列化性能以及与纯 javascript 解析器相似或更好的序列化性能。

      https://mongodb.github.io/node-mongodb-native/3.5/installation-guide/installation-guide/#bson-ext-module

      【讨论】:

        【解决方案3】:

        MongoDB 的查询执行速度非常快。但这也取决于您如何编写查询。用于获取前 10 个文档并将其按降序排序到集合中的 _id。您需要在查询中使用limitsort

        db.collectionName.find({}).limit(10).sort({_id:-1})
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2020-01-03
          • 2014-10-10
          • 2021-11-26
          • 2020-12-04
          • 2016-01-11
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多