08-查找不同的字段值
7.4 查找不同的字段值
使用MongoDB shell检索一组文档中指定字段的不同值 在本节中,您将编写一个MongoDB shell脚本,它使用方法distinct()检索不同的字段值,这些检索基于对示例数据库words的不同查询。这个练习旨在让您熟悉distinct()的各种使用方式。 程序清单7.11所示的示例执行distinct()操作,这些操作指定的参数key和query各不相同。对于每种操作返回的不同字段值数组,都使用printjson()将其显示到控制台。 请执行如下步骤,编写这个从示例数据集中检索不同字段值的脚本。 1.确保启动了MongoDB服务器。 2.确保运行了生成数据库words的脚本文件code/hour05/generate_words.js。 3.在文件夹code/hour07中新建一个文件,并将其命名为find_distinct.js。 4.在这个文件中输入程序清单7.11所示的代码。这些代码连接到数据库words,获取表示集合word_stats的Collection对象,并使用distinct()基于各种查询获取不同的字段值。 5.将这个文件存盘。 6.打开一个控制台窗口,并切换到目录code/hour07。 7.执行下面的命令以运行这个脚本,它从集合word_stats检索不同的字段值。程序清单7.12显示了这个脚本的输出。 程序清单7.11 find_distinct.js:在MongoDB shell中检索与查询匹配的文档中不同的字段值 程序清单7.12 find_distinct.js-output:在MongoDB shell中检索与查询匹配的文档中不同字段值的输出 ▲
一种很有用的MongoDB集合查询是,获取一组文档中某个字段的不同值列表。不同(distinct)意味着纵然有数千个文档,您只想知道那些独一无二的值。
Collection对象的方法distinct()让您能够找出指定字段的不同值列表,这种方法的语法如下:
distinct(key, [query])
其中参数key是一个字符串,指定了要获取哪个字段的不同值。要获取子文档中字段的不同值,可使用句点语法,如stats.count。参数query是一个包含标准查询选项的对象,指定了要从哪些文档中获取不同的字段值。
例如,假设有一些包含字段first、last和age的用户文档,要获取年龄超过65岁的用户的不同姓,可使用下面的操作:
lastNames =myUsers.distinct('last', { age: { $gt: 65} } );
方法distinct()返回一个数组,其中包含指定字段的不同值,例如:
["Smith", "Jones", ...]
▼ Try It Yourself
mongo find_distinct.js
01 mongo = new Mongo("localhost");
02 wordsDB = mongo.getDB("words");
03 wordsColl = wordsDB.getCollection("word_stats");
04 results = wordsColl.distinct('size');
05 print("Sizes of words:");
06 printjson(results);
07 results = wordsColl.distinct('size', {first:'q'});
08 print("Sizes of words starting with Q:");
09 printjson(results);
10 results = wordsColl.distinct('last', {'stats.vowels':0});
11 print("Words with no vowels end with letter:");
12 printjson(results);
13 results = wordsColl.distinct('first', {last:'u'});
14 print("Words ending in U start with letter:");
15 printjson(results);
16 print("Number of consonants in words longer than 10 characters:");
17 results = wordsColl.distinct('stats.consonants',{size:{$gt:10}});
18 printjson(results);
Sizes of words:
[ 3, 2, 1, 4, 5, 9, 6, 7, 8, 10, 11, 12, 13, 14 ]
Sizes of words starting with Q:
[ 8, 5, 7, 4, 11, 13 ]
Words with no vowels end with letter:
[ "y", "r", "v", "m", "s", "c", "h" ]
Words ending in U start with letter:
[ "y", "m", "b" ]
Number of consonants in words longer than 10 characters:
[ 6, 7, 8, 9, 5, 10 ]