-
Notifications
You must be signed in to change notification settings - Fork 2
/
basicExample.js
49 lines (49 loc) · 1.78 KB
/
basicExample.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/* basic books example */
/* sample documents */
db.books.insert([
{ "_id" : ObjectId("59457a75d975a00a7119a96d"), "title" : "The Great Gatsby", "language" : "English", "subjects" : [ "Long Island", "New York", "1920s" ] },
{ "_id" : ObjectId("59457a75d975a00a7119a96e"), "title" : "War and Peace", "language" : "Russian", "subjects" : [ "Russia", "War of 1812", "Napoleon" ] },
{ "_id" : ObjectId("59457a75d975a00a7119a96f"), "title" : "Open City", "language" : "English", "subjects" : [ "New York", "Harlem" ] }
]);
db.books.createIndex({language:1});
/* aggregation */
db.books.aggregate([
{"$match":{"language":"English"}},
{$unwind:"$subjects"},
{$group:{_id:"$subjects",count:{$sum:1}}},
{$sort:{count:-1}},
{$limit:3},
{$project:{_id:0,subject:"$_id", count:"$count"}}
]);
/* different aggregations with explain */
db.books.aggregate([
{"$match":{"language":"English"}},
{$unwind:"$subjects"},
{$group:{_id:"$subjects",count:{$sum:1}}},
{$sort:{count:-1}},
{$limit:3},
{$project:{_id:0,subject:"$_id", count:"$count"}}
], {explain:true});
db.books.aggregate([
{$unwind:"$subjects"},
{$group:{_id:"$subjects",count:{$sum:1}}},
{$sort:{count:-1}},
{$limit:3},
{$project:{_id:0,subject:"$_id", count:"$count"}}
], {explain:true});
db.books.aggregate([
{$unwind:"$subjects"},
{"$match":{"language":"English"}},
{$group:{_id:"$subjects",count:{$sum:1}}},
{$sort:{count:-1}},
{$limit:3},
{$project:{_id:0,subject:"$_id", count:"$count"}}
], {explain:true});
db.books.aggregate([
{$unwind:"$subjects"},
{"$match":{"language":"English","subjects":/^[ABC]/}},
{$group:{_id:"$subjects",count:{$sum:1}}},
{$sort:{count:-1}},
{$limit:3},
{$project:{_id:0,subject:"$_id", count:"$count"}}
], {explain:true});