-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSimple-MongoLabsCRUD.py
More file actions
87 lines (59 loc) · 2.3 KB
/
Simple-MongoLabsCRUD.py
File metadata and controls
87 lines (59 loc) · 2.3 KB
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
#!/usr/bin/python
# Copyright (c) 2015 ObjectLabs Corporation
# Distributed under the MIT license - http://opensource.org/licenses/MIT
__author__ = 'mongolab'
# Written with pymongo-2.6
# Documentation: http://api.mongodb.org/python/
# A python script connecting to a MongoDB given a MongoDB Connection URI.
import sys
import pymongo
### Create seed data
SEED_DATA = [
{
'decade': '1970s',
'artist': 'Debby Boone',
'song': 'You Light Up My Life',
'weeksAtOne': 10
},
{
'decade': '1980s',
'artist': 'Olivia Newton-John',
'song': 'Physical',
'weeksAtOne': 10
},
{
'decade': '1990s',
'artist': 'Mariah Carey',
'song': 'One Sweet Day',
'weeksAtOne': 16
}
]
### Standard URI format: mongodb://[dbuser:dbpassword@]host:port/dbname
MONGODB_URI = 'mongodb://user:pass@host:port/db'
###############################################################################
# main
###############################################################################
def main(args):
client = pymongo.MongoClient(MONGODB_URI)
db = client.get_default_database()
# First we'll add a few songs. Nothing is required to create the songs
# collection; it is created automatically when we insert.
songs = db['songs']
# Note that the insert method can take either an array or a single dict.
songs.insert(SEED_DATA)
# Then we need to give Boyz II Men credit for their contribution to
# the hit "One Sweet Day".
query = {'song': 'One Sweet Day'}
songs.update(query, {'$set': {'artist': 'Mariah Carey ft. Boyz II Men'}})
# Finally we run a query which returns all the hits that spent 10 or
# more weeks at number 1.
cursor = songs.find({'weeksAtOne': {'$gte': 10}}).sort('decade', 1)
for doc in cursor:
print ('In the %s, %s by %s topped the charts for %d straight weeks.' %
(doc['decade'], doc['song'], doc['artist'], doc['weeksAtOne']))
### Since this is an example, we'll clean up after ourselves.
db.drop_collection('songs')
### Only close the connection when your app is terminating
client.close()
if __name__ == '__main__':
main(sys.argv[1:])