如何使用MongoDB正确排序和更新大型收集文档?

时间:2015-07-29 11:45:13

标签: mongodb

我有一个包含超过100000个文档的集合,我需要获得 n recrods的排名以及总记录排名。

我试过了:

db.lineuppointsrecord.aggregate(    
  [      { $sort : {totalpoints: -1, _id: 1} }    
  ] )

db.lineuppointsrecord.find({},{totalpoints: true}).sort({totalpoints: -1, _id: 1})

然而,由于巨大的内存需求,这两者都失败了,这样做的正确方法是什么?

我不仅要对此进行排序,还要为每个名为rank的记录添加一个字段,该记录将是每个记录的totalpoints属性

2 个答案:

答案 0 :(得分:2)

来自在线文档页面:

$ sort和内存限制

  

$ sort阶段的RAM限制为100兆字节。默认情况下,如果   阶段超过此限制,$ sort将产生错误。允许   要处理大型数据集,请将allowDiskUse选项设置为   如果启用$ sort操作以写入临时文件,则为true。见   db.collection.aggregate()方法中的allowDiskUse选项和   有关详细信息的聚合命令。

答案 1 :(得分:2)

当没有索引可以为查询提供服务时,将应用内存限制。因此,答案是确保索引存在:

db.lineuppointsrecord.ensureIndex( { totalpoints: -1, _id: 1 } );

请注意,如果您有$ match阶段,则应首先在上面的复合索引中包含这些谓词。

请参阅aggregation and index in the documentation