-
Notifications
You must be signed in to change notification settings - Fork 0
/
grouping and aggregate.py
79 lines (70 loc) · 1.38 KB
/
grouping and aggregate.py
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# Given a collection of documents representing students, each containing fields like "name", "age", and "grade",
# write a MongoDB query to calculate the average age and average grade for each grade level.
import pymongo
from pymongo import MongoClient
from pprint import pprint
client = MongoClient('localhost',27017)
db = client['test']
students = db.students
students_data = [
{
"name": "Alice",
"age": 20,
"grade": "A"
},
{
"name": "Bob",
"age": 22,
"grade": "B"
},
{
"name": "Charlie",
"age": 21,
"grade": "C"
},
{
"name": "David",
"age": 23,
"grade": "A"
},
{
"name": "Eva",
"age": 24,
"grade": "B"
},
{
"name": "Frank",
"age": 22,
"grade": "A"
},
{
"name": "Grace",
"age": 21,
"grade": "C"
},
{
"name": "Henry",
"age": 20,
"grade": "B"
},
{
"name": "Ivy",
"age": 19,
"grade": "A"
},
{
"name": "Jack",
"age": 18,
"grade": "C"
}
]
students.insert_many(students_data)
query = [{
"$group":{"_id":"$grade",
"average_age":{"$avg":"$age"},
"count":{"$sum":1}}
},{
"$sort":{"_id":1}
}]
for student in students.aggregate(query):
pprint(student)