Pymongo for the Clueless

1,299 views

Published on

python, mongo, pymongo

Published in: Technology, Business
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
1,299
On SlideShare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
10
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Pymongo for the Clueless

  1. 1. PyMongo for the Clueless klrkdekira@gmail.com
  2. 2. http://www.python.org
  3. 3. http://www.mongodb.org/
  4. 4. ● json-like (bson) document store● full index support● replication and high availability● auto sharding● querying● fast in-place update● map/reduce● GridFS
  5. 5. SQL to Mongo MappingMySQL Term MongoTermdatabase databasetable collectionindex indexrow BSON documentcolumn BSON fieldjoin embedding and linkingprimary key _id field
  6. 6. PyMongoThe romantic story of and
  7. 7. Connection Part 1>>> import pymongo>>> conn = pymongo.Connection()is equivalent to>>> conn = pymongo.Connection(localhost, 27017)Getting the database>>> db = conn.testdbis equivalent to>>> db = conn[testdb]
  8. 8. Basic Part 2Getting the collection>>> collection = db.test_collectionalso is equivalent to>>> collection = db[test_collection]Make it understood from now
  9. 9. Insert New Document(s)>>> dummy = db[dummy]>>> dummy.insert({key: a, value: 1})ObjectId(4e7c50eb059bf61d2f000000)Multiple insert>>> docs = [{key:b, value:2}, {key:c, value:3}]>>> dummy.insert(docs)[ObjectId(4e7c552a059bf61d2f000002), ObjectId(4e7c552a059bf61d2f000003)]
  10. 10. Find Part 1>>> dummy.find_one(){u_id: ObjectId(4e7c50eb059bf61d2f000000), ukey: ua, uvalue: 1}>>> dummy.find()<pymongo.cursor.Cursor object at 0x2810ed0>>>> for d in dummy.find(): print d{u_id: ObjectId(4e7c50eb059bf61d2f000000), ukey: ua, uvalue: 1}{u_id: ObjectId(4e7c5544059bf61d2f000004), ukey: ub,uvalue: 2}{u_id: ObjectId(4e7c5544059bf61d2f000005), ukey: uc,uvalue: 3}
  11. 11. Find Part 2>>> dummy.find_one({key:a}){u_id: ObjectId(4e7c50eb059bf61d2f000000), ukey: ua, uvalue: 1}Query by ObjectId>>> from bson.objectid import ObjectId>>> dummy.find_one({_id:ObjectId(4e7c50eb059bf61d2f000000)}){u_id: ObjectId(4e7c50eb059bf61d2f000000), ukey: ua, uvalue: 1}Same goes with find.
  12. 12. Update>>> dummy.update({key:a}, {value:2})Update multiple document, destructive>>> dummy.update({key:a}, {value:2}, multi=True)Just to overwrite attributes>>> dummy.update({key:a}, {$set:{value:2}})
  13. 13. DeleteRemove multiple file>>> dummy.remove({key:a})Remove by ObjectId>>> dummy.remove({_id:ObjectId(4e7c50eb059bf61d2f000000)})
  14. 14. Stored JS>>> db.system.js.add = "function (x, y) { return x + y; }">>> db.system.js.add(1, 2)3.0>>> del db.system.js.add
  15. 15. QUESTION ?

×