【问题标题】:How to improve MongoDB performance with mongoose driver?如何使用 mongoose 驱动程序提高 MongoDB 性能?
【发布时间】:2018-07-15 05:07:38
【问题描述】:

我在 MongoDB 中有 2 个集合。

  1. 文档
  2. 数据

Document 有大约 5K 个文档,并且获得总数非常快。

但后来我又添加了一个集合Data,它有 1M 条记录。现在,如果我尝试获取 Document 中的记录总数,它在 Mongoose 中需要 20 秒。但在 Mongo 控制台中它更快。

//文档架构

var docSchema = mongoose.Schema({
            docId: String,
            articleid: String,
            title:String,
            lastModified: String,
});
docSchema.index({ docId: 1, articleid: 1 ,lastModified:1});
var Doc = mongoose.model('document', docSchema);

module.exports = Doc;

//数据架构

var allData = mongoose.Schema({
    _id:String,
    id: Number,
    author:String,    
});
allData.index({ id: 1});
var data = mongoose.model('Data', allMetricsData);

module.exports = data;

而Node.JS中的聚合函数是这样的:

 Document.count(function(errs, count) {
   console.log("Count is:",count);
 });

那么如何使用 Mongoose 提高性能呢?

当我执行时,db.documents.count() 我会立即得到响应。

【问题讨论】:

  • 你能把你的猫鼬查询粘贴到这里吗?

标签: node.js mongodb mongoose mongoose-populate


【解决方案1】:

首先,不要忘记为查询中使用的所有主要字段添加索引。

例如,如果您的所有查询都使用“名称”:

Collection.find({name: "aaa"})

或“姓名”和“年龄”:

Collection.find({name:"aaa", "age": 4})

将索引放入模型中,如下所示:

var mongoose = require("mongoose")

ActionCode = new mongoose.Schema({
    name:                   {type: String, default: ""},
    age:                    {type:Number, default: 0},
    otherfield:             {type:Number, default: 0},
});

ActionCode.index({name:1});
ActionCode.index({name:1, age: 1});

module.exports = mongoose.model('ActionCode', ActionCode);

您的索引将被推入内存,据此文档的分辨率将更快。

https://docs.mongodb.com/manual/indexes/

然后,由于返回文档的数量,它可能需要一些时间,只选择需要的字段,这样 mongo 将返回到您的服务器只需要的字段而不是整个文档:

例如,如果您只需要姓名、年龄和类型字段:

 Collection.find({name: "aaa"},{name:1, age:1, field:1}, function(err, response){

        // returned documents here contains only following fields: _id, name, age, field

=======

试试

 Collection.find({}).select({_id: 1}).count(function(err, result)

或者尝试聚合:

Collection.aggregate([{$group:{_id: null, count:{$sum :1}}])

【讨论】:

  • 聚合函数运行缓慢的原因可能是什么? Mongo 不能处理一百万条记录吗?
  • 1/ 未命中索引,2/ 返回数据量,3/ 聚合内部优化
  • 添加了索引,仍然没有变化。我正在对有 5K 条记录的集合进行汇总,这将如何影响?
  • 所以你必须改进你的聚合代码,只选择需要的字段,优化你的匹配......如果你需要更多帮助,请显示你的聚合和数据结构
  • 用代码更新了问题。当我在 mongo shell 中执行 db.documents.count() 时,我会立即得到结果。
猜你喜欢
  • 2011-10-14
  • 1970-01-01
  • 2016-07-11
  • 1970-01-01
  • 2013-08-16
  • 2018-07-03
  • 1970-01-01
  • 2014-07-04
  • 1970-01-01
相关资源
最近更新 更多