performance - mongoose 在这种情况下子文档和全局之间的性能有什么区别吗?

标签 performance node.js mongodb

案例1

var MessageSchema = new Schema({
  text: {type: String, required: true}
});

var UserSchema = new Schema({
    ..
  messages: {type: [MessageSchema], required: false}
});

UserSchema.find({_id:id},'messages',function(err, messages){
  // case 1
});

对比

案例2

var MessageSchema = new Schema({
  text: {type: String, required: true},
  userId: {type:Schema.Types.ObjectId, required: true}
});
MessageSchema.find({userId:id}, function(err, messages){
  //case 2
});

我只知道mongodb如何操作这两个方法。

最佳答案

我假设您正在比较为用户查找所有文档的方法。

在第一种情况下,_id 将自动索引,因此查找速度会很快,并且当用户文档加载时将加载消息。

在第二种情况下,假设您在消息 userID 上添加索引,那么 find 将在索引中查找 userID 并加载与 userID 匹配的所有文档。

因此,如果您要优化查找和访问消息,第一种情况应该总是更快。

但是,如果您正在优化消息添加,并且您有大量消息并且经常添加新消息,则在第一种情况下,用户文档将会增长和移动。它可能会达到文档大小限制。正在保存更大的文档。

有关更多详细信息,请参阅本指南,其中对引用文献和嵌入文档之间的权衡进行了很好的讨论。

http://docs.mongodb.org/manual/MongoDB-data-models-guide.pdf

我希望这会有所帮助。

关于performance - mongoose 在这种情况下子文档和全局之间的性能有什么区别吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20753824/

相关文章:

performance - 写入操作成本

node.js - 如何使用 Redis 作为缓存系统使用 Node 开发 REST API?

node.js - Node : does a find query to select n last records need to run asynchronously

node.js - 为什么 CSRF token 要加密?

javascript - 无法使用 Jade 在选项卡中插入表格

mysql - 选择中的计数子查询 - mongoDB

java - MongoDB聚合查询转java代码

c++ - C++中的缓存(或多或少适合初学者)

c++ - 分配给堆与堆栈的执行时间有何不同?

mysql - 速度和性能优化问题: Multiple database model vs single database