PyMongo
- PyMongo is a Python library that enables us to connect with MongoDB and perform all database operations on MongoDB database.
- This is a third party library. So, you need to install it to use.
pip install pymongo
. - Official documentation site: link
import pymongo
import datetime
from bson.objectid import ObjectId
#### DATA ####
post = {"author": "Mike",
"text": "My first blog post!",
"tags": ["mongodb", "python", "pymongo"],
"date": datetime.datetime.utcnow()}
new_posts = [{"author": "Mike",
"text": "Another post!",
"tags": ["bulk", "insert"],
"date": datetime.datetime(2009, 11, 12, 11, 14)},
{"author": "Eliot",
"title": "MongoDB is fun",
"text": "and pretty easy too!",
"date": datetime.datetime(2009, 11, 10, 10, 45)}]
d = datetime.datetime(2009, 11, 12, 12)
#################################################################
Description | Code |
---|---|
Connect To mongodb | client = MongoClient('mongodb://localhost:27017/') client = pymongo.MongoClient("localhost", 27017) |
returns list of databases | client.list_database_names() |
Create/switch to database | db = client['test-database'] db = client.test_database |
Returns list of collections | db.list_collection_names() |
Create new collection | collection = db.test_collection collection = db['test-collection'] |
Delete the collection | collection.drop() # |
Find Operation 1. Returns first document 2. Returns first doc which satisfy given query 3. String format of post_id will not work |
1. collection.find_one() 2. collection.find_one({"author": "Mike"}) 3. collection.find_one({'_id': ObjectId(post_id)}) |
Returns a list, docs will have address and name, 0 allowed only for id | collection.find({"author": "Mike"}, {"name": 1, "address": 1 }) |
Output in order; -1 > Descending, 1 > ascending | collection.find({"author": "Mike"}).sort("title", -1) |
Date value is less than given date d | collection.find({"date": {"$lt": d}}) |
Returns only 5 documents | collection.find({"author": "Mike"}).limit(5) |
Delete one document | collection.delete_one({"address": "Mountain 21"}) |
Delete multiple documents | collection.delete_many({"author": "Mike"}) # |
Delete all docs of collection | collection.delete_many({}) |
Returns deleted docs count | collection.delete_many().deleted_count |
Count of all document in the collection | collection.count_documents({"author": "Mike"}) |
Insert a single document | collection.insert_one(post) collection.insert_one(post).inserted_id |
Insert Multiple documents | collection.insert_many(new_posts) collection.insert_many(new_posts).inserted_ids |
Update document if we dont specify $set , it will replace whole doc |
collection.update_one(myquery, {"$set": {"address": "Canyon 123"}}) collection.update_many(myquery, newvalues).modified_count |
queries¶
Description | Query |
---|---|
Greater than | "$gt": "S" |
Regular expression | "$regex": "^S" |