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

03-对结果集进行排序

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

7.2 对结果集进行排序

使用sort()以特定顺序返回MongoDB shell Cursor对象表示的文档 在本节中,您将编写一个MongoDB shell脚本,在其中使用sort()根据字段值以不同顺序排列从示例数据库words返回的文档。程序清单7.3所示的示例执行各种find()操作,并使用sort()对返回的文档进行排序。 方法displayWords()设置单词的输出格式,并使用方法map()来迭代游标。请注意,单词的显示顺序随方法sort()中指定的字段和值而异。 请执行如下步骤,编写这个在数据库words中查找文档并以特定顺序显示它们的脚本。 1.确保启动了MongoDB服务器。 2.确保运行了生成数据库words的脚本文件code/hour05/generate_words.js。 3.在文件夹code/hour07中新建一个文件,并将其命名为find_sort.js。 4.在这个文件中输入程序清单程序清单7.3所示的代码。这些代码连接到数据库words,获取表示集合word_stats的Collection对象,使用find()来检索单词,并使用sort()来控制文档的显示顺序。 5.将这个文件存盘。 6.打开一个控制台窗口,并切换到目录code/hour07。 7.执行下面的命令以运行这个脚本,它对集合word_stats执行各种查询,并对返回的文档进行排序。程序清单7.4显示了这个脚本的输出。 程序清单7.3 find_sort.js:在MongoDB shell中对Cursor对象表示的文档进行排序 程序清单7.4 find_sort.js-output:在MongoDB shell中对Cursor对象表示的文档进行排序的输出

从MongoDB数据库检索文档时,一个重要方面是对找到的文档进行排序。在只想取回特定数量的文档(如前10个)或要对结果集进行分页时,这特别有用。Options对象提供了sort选项,让您能够指定用于排序的文档字段和方向。

Cursor对象的方法sort()让您能够指定要根据哪些字段对游标中的文档进行排序,并按相应的顺序返回文档。方法sort()将一个对象作为参数,这个对象将字段名用作属性名,并使用值1(升序)和-1(降序)来指定排序顺序。

例如,要按字段name降序排列,可使用下面的代码:

myCollection.find().sort({name:1}).sort({value:-1});

对于同一个游标,可多次使用sort(),从而依次按不同的字段进行排序。例如,要首先按字段name升序排列,再按字段value降序排列,可使用下面的代码:

myCollection.find().sort({name:1}).sort({value:-1});

▼ Try It Yourself

mongo find_sort.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({first:'w'});
15 print("Words starting with w ascending:");
16 displayWords(cursor.sort({word:1}));
17 cursor = wordsColl.find({first:'w'});
18 print("\nWords starting with w descending:");
19 displayWords(cursor.sort({word:-1}));
20 print("\nQ words sorted by last letter and by size: ");
21 cursor = wordsColl.find({first:'q'});
22 displayWords(cursor.sort({last:1, size:-1}));
23 print("\nQ words sorted by size then by last letter: ");
24 cursor = wordsColl.find({first:'q'});
25 displayWords(cursor.sort({size:-1}).sort({last:1}));
26 print("\nQ words sorted by last letter then by size: ");
27 cursor = wordsColl.find({first:'q'});
28 displayWords(cursor.sort({last:1}).sort({size:-1}));
Words starting with w ascending:
["wage","wagon","waist","wait","wake","wake","walk...
Words starting with w descending:
["wrong","wrong","written","writing","writer","wri...
Q words sorted by last letter and by size:
["questionnaire","quite","quote","quote","quarterb...
Q words sorted by size then by last letter:
["quite","quote","questionnaire","quote","quick","...
Q words sorted by last letter then by size:
["questionnaire","quarterback","question","questio...