-
Notifications
You must be signed in to change notification settings - Fork 0
/
pymongo_demo.py
179 lines (146 loc) · 4.75 KB
/
pymongo_demo.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
#!usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Simple usage demo of pymongo library (driver).
Before running this script, first make sure MongoDB server is up and running.
"""
__author__ = 'Ziang Lu'
from datetime import datetime
from pymongo import (
ASCENDING, DESCENDING, InsertOne, MongoClient, TEXT, UpdateOne
)
def init_db() -> None:
"""
Initialize a DB by inserting documents.
:return: None
"""
# Connect to MongoDB server
cli = MongoClient()
print(cli)
# Select "test" database; create "test" database if it doesn't exist
db = cli.test
print(db)
# Select "posts" collection; create "posts" collection if it doesn't exist
posts = db.posts
print(posts)
# Insert documents
first_post = {
'author': 'Ziang',
'title': 'First Post',
'content': 'What to write...',
'tags': ['diary', 'python'],
'date': datetime.now()
}
inserted_id = posts.insert_one(first_post).inserted_id
print(f'Just inserted: {inserted_id}')
inserted_ids = posts.insert_many([
{
'author': 'Mike',
'title': 'Second Post',
'tags': ['diary'],
'date': datetime.now()
},
{
'author': 'Ziang',
'title': 'Third Post',
'tags': ['diary'],
'date': datetime.now()
}
]).inserted_ids
print(f'Just inserted: {inserted_ids}')
print('Finished DB initialization')
# Show all the collections in "test" database
print(f'Existing collections: {db.list_collection_names()}')
def query_db() -> None:
"""
Queries "test" DB.
:return: None
"""
cli = MongoClient()
db = cli.test
posts = db.posts
print(f"Documents with author 'Ziang': "
f"{posts.count_documents({'author': 'Ziang'})}")
for post in posts.find(
{'author': 'Ziang'},
projection={'_id': False, 'tags': False, 'date': False}
):
print(post)
print("Same result sorted by 'title':")
for post in posts.find(
{'author': 'Ziang'},
projection={'_id': False, 'tags': False, 'date': False},
).sort('title', ASCENDING):
print(post)
def update_db() -> None:
"""
Updates the DB by updating the documents.
:return: None
"""
cli = MongoClient()
db = cli.test
posts = db.posts
update_result = posts.update_many(
{'author': 'Ziang'}, update={'$set': {'rank': 1}}
)
print(f'Number of updated documents: {update_result.modified_count}')
####################
# We can also do bulk write as follows:
requests = [
InsertOne({'x': 1}),
UpdateOne({'author': 'Ziang'}, update={'$set': {'rank': 1}})
]
write_result = posts.bulk_write(requests)
print(f'Number of inserted documents: {write_result.inserted_count}')
print(f'Number of updated documents: {write_result.modified_count}')
def test_index() -> None:
"""
Tests index-related stuff.
:return: None
"""
cli = MongoClient()
db = cli.test
posts = db.posts
# Single-Field Index
posts.create_index([('title', ASCENDING)], unique=True) # "title" must be unique
# Compound Index
posts.create_index([('title', ASCENDING), ('date', DESCENDING)])
# Text Index
posts.create_index([('title', TEXT)])
print(list(posts.index_information()))
# Check index
posts.insert_one({
'author': 'Ziang',
'title': 'Fourth Post'
}) # This is fine.
posts.insert_one({
'author': 'Ziang',
'title': 'Fourth Post'
}) # DuplicateKeyError
if __name__ == '__main__':
init_db()
# Output:
# MongoClient(host=['localhost:27017'], document_class=dict, tz_aware=False, connect=True)
# Database(MongoClient(host=['localhost:27017'], document_class=dict, tz_aware=False, connect=True), 'test')
# Collection(Database(MongoClient(host=['localhost:27017'], document_class=dict, tz_aware=False, connect=True), 'test'), 'posts')
# Just inserted: ObjectId(5c341c987cb9471ee3934d71)
# Just inserted: [ObjectId('5c341c997cb9471ee3934d72'), ObjectId('5c341c997cb9471ee3934d73')]
# Finished DB initialization
# Existing collections: ['posts']
query_db()
# Output:
# Documents with author 'Ziang': 2
# {'author': 'Ziang', 'title': 'First Post', 'content': 'What to write...'}
# {'author': 'Ziang', 'title': 'Third Post'}
# Same result sorted by 'title':
# {'author': 'Ziang', 'title': 'First Post', 'content': 'What to write...'}
# {'author': 'Ziang', 'title': 'Third Post'}
update_db()
# Output:
# Number of updated documents: 2
#
# Number of inserted documents: 1
# Number of updated documents: 0
test_index()
# Output:
# ['_id_', 'title_1']