-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathscript.py
36 lines (28 loc) · 975 Bytes
/
script.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
"""
Script to parse course information from courses.json, create the appropriate databases and
collection(s) on a local instance of MongoDB, create the appropriate indices (for efficient retrieval)
and finally add the course data on the collection(s).
"""
import pymongo
import json
# Connect to MongoDB
client = pymongo.MongoClient("mongodb://localhost:27017/")
db = client["courses"]
collection = db["courses"]
# Read courses from courses.json
with open("courses.json", "r") as f:
courses = json.load(f)
# Create index for efficient retrieval
collection.create_index("name")
# add rating field to each course
for course in courses:
course['rating'] = {'total': 0, 'count': 0}
# add rating filed to each chapter
for course in courses:
for chapter in course['chapters']:
chapter['rating'] = {'total': 0, 'count': 0}
# Add courses to collection
for course in courses:
collection.insert_one(course)
# Close MongoDB connection
client.close()