0% found this document useful (0 votes)
0 views

TP2_BD_MongoDB_Python

The document provides a comprehensive guide on using PyMongo, a Python module for interacting with MongoDB. It covers installation, creating and managing collections, querying data, filtering, projections, and sorting documents with practical code examples. Each section illustrates specific functionalities such as inserting, listing, dropping collections, and counting documents in a MongoDB database.

Uploaded by

hmercha.sarra
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

TP2_BD_MongoDB_Python

The document provides a comprehensive guide on using PyMongo, a Python module for interacting with MongoDB. It covers installation, creating and managing collections, querying data, filtering, projections, and sorting documents with practical code examples. Each section illustrates specific functionalities such as inserting, listing, dropping collections, and counting documents in a MongoDB database.

Uploaded by

hmercha.sarra
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

2024-2025

TP : MongoDB avec Python


Enseignant : Dr. Abdelkarim Mars Section : Info_2

PyMongo
PyMongo is a Python module for working with MongoDB in Python.

Installing PyMongo
The following command is used to install PyMongo.

$ sudo pip install pymongo

We install PyMongo with pip.

PyMongo create collection


In the first example, we create a new collection. MongoDB stores documents in collections.
Collections are analogous to tables in relational databases.

create_collection.py
#!/usr/bin/python3

from pymongo import MongoClient

cars = [ {'name': 'Audi', 'price': 52642},


{'name': 'Mercedes', 'price': 57127},
{'name': 'Skoda', 'price': 9000},
{'name': 'Volvo', 'price': 29000},
{'name': 'Bentley', 'price': 350000},
{'name': 'Citroen', 'price': 21000},
{'name': 'Hummer', 'price': 41400},
{'name': 'Volkswagen', 'price': 21600} ]

client = MongoClient('mongodb://localhost:27017/')

with client:

db = client.testdb

db.cars.insert_many(cars)

PyMongo list collections


With collection_names, we get list available collections in the database.

list_collections.py
#!/usr/bin/python3

from pymongo import MongoClient

client = MongoClient('mongodb://localhost:27017/')

with client:
db = client.testdb
print(db.collection_names())

The example prints collections in the testdb database.

PyMongo drop collection


The drop method removes a collection from the database.

drop_collection.py
#!/usr/bin/python3

from pymongo import MongoClient

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

from pymongo import MongoClient

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))

PyMongo read all data


In the following example, we read all records from the collection. We use Python for loop to traverse the
returned cursor.

all_cars.py
#!/usr/bin/python3
from pymongo import MongoClient

client = MongoClient('mongodb://localhost:27017/')

with client:

db = client.testdb

cars = db.cars.find()

for car in cars:


print('{0} {1}'.format(car['name'],
car['price']))

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.

for car in cars:


print('{0} {1}'.format(car['name'],
car['price']))

With the Python for loop, we iterate over the result set.

PyMongo count documents


The number of documents is retrieved with the count method.

count_cars.py
#!/usr/bin/python3

from pymongo import MongoClient

client = MongoClient('mongodb://localhost:27017/')

with client:

db = client.testdb

n_cars = db.cars.find().count()

print("There are {} cars".format(n_cars))

The example counts the number of cars in the collection with count.

$ ./count_cars.py
There are 8 cars

There are eight cars in the collection.

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

expensive_cars = db.cars.find({'price': {'$gt': 50000}})

for ecar in expensive_cars:


print(ecar['name'])

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

from pymongo import MongoClient

client = MongoClient('mongodb://localhost:27017/')

with client:

db = client.testdb

cars = db.cars.find({}, {'_id': 1, 'name':1})

for car in cars:


print(car)

The example prints the _id and name fields of the documents.

cars = db.cars.find({}, {'_id': 1, 'name':1})

We can specify either including or excluding projections, not both at the same time.

PyMongo sorting documents


We can sort documents with sort.

sorting.py
#!/usr/bin/python3

from pymongo import MongoClient, DESCENDING

client = MongoClient('mongodb://localhost:27017/')

with client:

db = client.testdb

cars = db.cars.find().sort("price", DESCENDING)

for car in cars:


print('{0} {1}'.format(car['name'],
car['price']))

You might also like