TP2_BD_MongoDB_Python
TP2_BD_MongoDB_Python
PyMongo
PyMongo is a Python module for working with MongoDB in Python.
Installing PyMongo
The following command is used to install PyMongo.
create_collection.py
#!/usr/bin/python3
client = MongoClient('mongodb://localhost:27017/')
with client:
db = client.testdb
db.cars.insert_many(cars)
list_collections.py
#!/usr/bin/python3
client = MongoClient('mongodb://localhost:27017/')
with client:
db = client.testdb
print(db.collection_names())
drop_collection.py
#!/usr/bin/python3
client = MongoClient('mongodb://localhost:27017/')
with client:
db = client.testdb
db.cars.drop()
The example removes the cars collection from the testdb database.
PyMongo cursor
The find methods return a PyMongo cursor, which is a reference to the result set of a query.
cursor.py
#!/usr/bin/python3
client = MongoClient('mongodb://localhost:27017/')
with client:
db = client.testdb
cars = db.cars.find()
print(cars.next())
print(cars.next())
print(cars.next())
cars.rewind()
print(cars.next())
print(cars.next())
print(cars.next())
print(list(cars))
all_cars.py
#!/usr/bin/python3
from pymongo import MongoClient
client = MongoClient('mongodb://localhost:27017/')
with client:
db = client.testdb
cars = db.cars.find()
The example prints all car names and their prices from the collection.
cars = db.cars.find()
The find method selects documents in a collection or view and returns a cursor to the selected
documents. A cursor is a reference to the result set of a query.
With the Python for loop, we iterate over the result set.
count_cars.py
#!/usr/bin/python3
client = MongoClient('mongodb://localhost:27017/')
with client:
db = client.testdb
n_cars = db.cars.find().count()
The example counts the number of cars in the collection with count.
$ ./count_cars.py
There are 8 cars
PyMongo filters
The first parameter of find and find_one is a filter. The filter is a condition that all documents must match.
filtering.py
#!/usr/bin/python3
from pymongo import MongoClient
client = MongoClient('mongodb://localhost:27017/')
with client:
db = client.testdb
The example prints the names of cars whose price is greater than 50000.
PyMongo projections
With projections, we can select specific fields from the returned documents. The projections are passed in the
second argument of the find method.
projection.py
#!/usr/bin/python3
client = MongoClient('mongodb://localhost:27017/')
with client:
db = client.testdb
The example prints the _id and name fields of the documents.
We can specify either including or excluding projections, not both at the same time.
sorting.py
#!/usr/bin/python3
client = MongoClient('mongodb://localhost:27017/')
with client:
db = client.testdb