查询所有文档集合的最快方法

时间:2017-05-13 23:13:02

标签: mongodb performance mongoose

我的收藏品大约有500份文件,几周后会翻倍:

如何更快地获取所有文件?我目前正在使用db.registrations.find(),这样我就可以拥有所有可用于搜索,排序和过滤数据的文档。使用跳过/限制可以快速显示查询,但是您无法搜索玩家的所有注册,这是必要的。

我的架构:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var playerSchema = new mongoose.Schema({
  first: {
    type: String,
    required: true
  },
  last: {
    type: String,
    required: true
  },
  email: {
    type: String,
    required: true
  },
  phone: {
    type: String,
    required: true
  },
  address: {
    address: String,
    city: String,
    state: String,
    zip: String,
    country: {
      type: String,
      "default" : "USA"
    },
    adult: Boolean
  }

});

var registrationsSchema = new mongoose.Schema({
  event : {
    type: String,
    required: true
  },
  day : {
    type: String,
    required: true
  },
  group : {
    type: String,
    required: true
  },
  field : {
    type: String,
  },
  price : {
    type: Number,
    required: true
  },
  players : [playerSchema],
  net : Number,
  team : {
    type: Number,
    min: 0,
    max: 7,
    "default" : null
  },
  notes: String,
  paymentID : {
    type: String,
    required: true,
    "default": "VOLUNTEER"
  },
  paymentStatus : {
    type: String,
    "default" : "PAID"
  },
  paymentNote : String,
  // users : [userSchema],
  active : {
   type: Boolean,
   default: true
  },
  users: [{
        type: Schema.Types.ObjectId,
        ref: 'User'
    }],
  createdOn : {
    type : Date,
    "default" : Date.now
  },
  updatedLast : {
    type: Date
  }
});

mongoose.model('Registration', registrationsSchema);

2 个答案:

答案 0 :(得分:2)

使用mongoose从mongodb加载1000条记录没什么大不了的。我过去做过(2-3k记录),只要我遵守这两条规则就行得很好:

不要加载所有的猫鼬东西

使用lean查询。 它不会加载所有mongoose方法/属性,只加载对象中的数据。您无法使用.save()或其他方法,但加载的速度更快。

使用流来加载数据。

Streams是使用nodejs / mongoose加载大型数据集的好方法。它将从mongodb逐块读取数据并将其发送到您的应用程序以供使用。你会避免这个典型案例:

  
      
  • 我的数据等待2秒,我的服务器空闲
  •   
  • 我的服务器在2秒内是100%CPU来处理我得到的数据并且数据库空闲。
  •   
     

使用流,在此示例中,您的总时间将是~2s而不是2 + 2 = 4s

要使用mongoose从流加载数据,请使用.cursor()功能将您的请求更改为nodejs stream

以下是快速加载所有玩家的示例

const allPlayers = [];

const cursor = Player.find({}).lean().cursor();
cursor.on('data', function(player) { allPlayers.push(player); }).
cursor.on('end', function() { console.log('All players are loaded here'); });

答案 1 :(得分:1)

您可以使用以下方式实现目标。

  1. 默认情况下,如果您查询mongoose文档,它将加载其所有属性和所需的其他必要元数据(即,使用lean = false)。因此,如果你使用lean()函数,它将只加载一个普通的java脚本对象,它甚至不会返回setter和相应的getter方法。这样你就可以非常快速地获得所有文件。而你将获得高性能。这就是瘦()在背景上的神奇功能。

  2. 另一个建议是作为一个拇指规则,请根据您对每个集合的要求维护正确的索引,以便在查询时获得良好的性能。

  3. 希望这会对你有帮助!

相关问题