PyMongo is a Python driver for MongoDB, a popular NoSQL database. MongoDB is a document-oriented database that stores data in flexible, JSON-like documents, and PyMongo allows Python applications to interact with MongoDB.
With PyMongo, you can perform various database operations, such as inserting, updating, deleting, and querying documents. It provides a convenient and Pythonic way to work with MongoDB, allowing you to use Python data structures and idioms directly.
Install PyMongo
pip install pymongo
Connect to MongoDB
import pymongo # Connect to MongoDB server (default: localhost, port: 27017)
client = pymongo.MongoClient("mongodb://localhost:27017/")
Create or Select a Database
# Create or select a database
mydatabase = client["mydatabase"]
Create or Select a Collection
# Create or select a collection
mycollection = mydatabase["mycollection"]
Use the sort()
method to sort the result in ascending or descending order.
The sort()
method takes one parameter for “field name” and one parameter for “direction” (ascending is the default direction)
import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"] mydoc = mycol.find().sort("name") #for descending .sort("name",-1)
for x in mydoc: print(x)
Insert Documents
# Insert a single document
document = {"name": "John", "age": 30, "city": "New York"}
result = mycollection.insert_one(document)
print(f"Inserted document ID: {result.inserted_id}")
Insert Multiple Documents
# Insert multiple documents
documents = [ {"name": "Alice", "age": 25, "city": "San Francisco"}, {"name": "Bob", "age": 35, "city": "Los Angeles"}
]
result = mycollection.insert_many(documents)
print(f"Inserted {len(result.inserted_ids)} documents")
Delete one document
# Delete a document
mycollection.delete_one({"name": "John"})
Delete multiple documents
# Delete multiple documents
mycollection.delete_many({"city": "Brooklyn"})
Delete all documents in a collections
x = mycol.delete_many({}) print(x.deleted_count, " documents deleted.")
Delete a collection
import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"] mycol.drop()
Update a single documents
# Update a document
mycollection.update_one({"name": "John"}, {"$set": {"age": 31}})
alternate method
import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"] myquery = { "address": "Valley 345" }
newvalues = { "$set": { "address": "Canyon 123" } } mycol.update_one(myquery, newvalues) #print "customers" after the update:
for x in mycol.find(): print(x)
Update multiple documents
# Update multiple documents
mycollection.update_many({"city": "New York"}, {"$set": {"city": "Brooklyn"}})
To select data from a collection in MongoDB, we can use the find_one()
method.
The find_one()
method returns the first occurrence in the selection.
import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"] x = mycol.find_one() print(x)
To select data from a table in MongoDB, we can also use the find()
method.
The find()
method returns all occurrences in the selection.
The first parameter of the find()
method is a query object. In this example we use an empty query object, which selects all documents in the collection.
import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"] for x in mycol.find(): print(x)
using second parameter in find()
import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"] for x in mycol.find({},{ "_id": 0, "name": 1, "address": 1 }): print(x)
Filter the result
When finding documents in a collection, you can filter the result by using a query object.
The first argument of the find()
method is a query object, and is used to limit the search.
import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"] myquery = { "address": "Park Lane 38" } mydoc = mycol.find(myquery) for x in mydoc: print(x)
Advance query
import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"] myquery = { "address": { "$gt": "S" } } mydoc = mycol.find(myquery) for x in mydoc: print(x)
Limit the query result
import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"] myresult = mycol.find().limit(5) #print the result:
for x in myresult: print(x)
Discover more from Coursity
Subscribe to get the latest posts sent to your email.