当前位置:嗨网首页>书籍在线阅读

05-限制结果集的大小

  
选择背景色: 黄橙 洋红 淡粉 水蓝 草绿 白色 选择字体: 宋体 黑体 微软雅黑 楷体 选择字体大小: 恢复默认

7.3.1 限制结果集的大小

使用limit()将MongoDB shell Cursor对象表示的文档减少到指定的数量 在本节中,将对多个数据集执行方法limit(),以演示如何限制find()操作返回的结果。程序清单7.5所示的示例执行各种find()操作,并使用limit()来限制Cursor对象表示的文档数量。 方法displayWords()设置单词的输出格式,并使用方法map()迭代游标。请注意,也显示了原始Cursor对象表示的文档数。 请执行下面的步骤,编写这个在数据库words中查找文档并显示文档数的脚本。 1.确保启动了MongoDB服务器。 2.确保运行了生成数据库words的脚本文件code/hour05/generate_words.js。 3.在文件夹code/hour07中新建一个文件,并将其命名为find_limit.js。 4.在这个文件中输入程序清单7.5所示的代码。这些代码连接到数据库words,获取表示集合的Collection对象,使用find()和各种查询运算符检索单词,并使用limit()减少要迭代并显示的文档数。 5.将这个文件存盘。 6.打开一个控制台窗口,并切换到目录code/hour07。 7.执行下面的命令以运行这个脚本,它限制各个针对集合word_stats的查询返回的文档数。程序清单7.6显示了这个脚本的输出。 程序清单7.5 find_limit.js:在MongoDB shell中限制Cursor对象返回的文档数 程序清单7.6 find_limit.js-output:在MongoDB shell中限制Cursor对象返回的文档数的输出

要限制find()或其他查询请求返回的数据量,最简单的方法是对find()操作返回的Cursor对象调用方法limit(),它让Cursor对象返回指定数量的文档,可避免检索的对象量超过应用程序的处理能力。

例如,下面的代码只显示集合中的前10个文档,即便匹配的文档有数千个:

cursor = wordsColl.find();
cursor = cursor.limit(10);
cursor.forEach(function(word){
   printjson(word);
});

▼ Try It Yourself

mongo find_limit.js
01 function displayWords(cursor){
02    words = cursor.map(function(word){
03       return word.word;
04    });
05    wordStr = JSON.stringify(words);
06    if (wordStr.length > 65){
07       wordStr = wordStr.slice(0, 50) + "...";
08    }
09    print(wordStr);
10 }
11 mongo = new Mongo("localhost");
12 wordsDB = mongo.getDB("words");
13 wordsColl = wordsDB.getCollection("word_stats");
14 cursor = wordsColl.find();
15 print("Total Words :", cursor.count());
16 print("Limiting to 10: ");
17 displayWords(cursor.limit(10));
18 cursor = wordsColl.find({first:'p'});
19 print("Total Words starting with p :", cursor.count());
20 print("Limiting to 3: ");
21 displayWords(cursor.limit(3));
22 cursor = wordsColl.find({first:'p'});
23 print("Limiting to 5: ");
24 displayWords(cursor.limit(5));
Total Words : 5011
Limiting to 10:
["the","be","and","of","a","in","to","have","to","it"]
Total Words starting with p : 406
Limiting to 3:
["people","put","problem"]
Limiting to 5:
["people","put","problem","part","place"]