Python MongoDB
Install Mongodb Driver
PyMongo
pip install pymongo
Sample
from pymongo import MongoClient client = MongoClient() db = client.mydb # mydb is database name client['mydb'] client.close()
client is mongo client, db is database object.
This is similar as mongoshell
About mongoshell, please look MongoDB Basic Use
Insert
client = MongoClient() db = client.mydb # mydb is database name client['mydb'] #coll = db.users # users is collection name db.user.insert_one({"name":"dj110", "attr":{"bloodtype": "AB", "play":"soccer"}}) db.user.insert_one({"name":"kotori", "team":"us", "grade" : "2"}) db.user.insert_one({"name":"hanayo", "team":"us", "grade" : "1"}) client.close()
Retrieve
def printAll(cursor): for document in cursor: print(document) cursor = db.user.find() printAll(cursor) cursor = db.user.find({"name":"kotori"}) printAll(cursor) cursor = db.user.find({"$or": [{"team": "junior"}, {"grade": "1"}]}) printAll(cursor)
Others
update_one, update_many, replace_one, delete_one, delete_many, db.user.drop()