MongoDb : Python Driver

Last update on April 14 2018 06:14:57 (UTC/GMT +8 hours)

Introduction

The PyMongo distribution contains tools for interacting with MongoDB database from Python. This tutorial covers installing PyMongo on various operating systems, connection and basic database operation like insert, update, delete and searching with PyMongo.

Installing with pip

pip is a tool for installing and managing Python packages. Use pip to install PyMongo on platforms other than Windows.

To complete the installation operation, root or administrator privileges may be required.

Before installing the Python distribution on your system, enable python.exe in Windows %PATH% setting ( path environment variable) or manually add it to, if it is not enabled.

Installing the Windows Driver :
Select and download the MSI installer packages from here as per your requirement.

Working with MongoDB and PyMongo

We assumes that a MongoDB instance is running on the default host and port. Before you start, make sure that you have the PyMongo distribution installed. In the Python shell, the following should run without raising an exception :

>>> import pymongo
>>>

Making a Connection with MongoClient

To create a MongoClient to the running mongod instance execute the following code :

A single instance of MongoDB can support multiple independent databases. Here is the command :

>>> db = client.testdb

or (using dictionary style access):

>>> db = client['testdb']

Insert a document

To insert a document into a collection you can use the insert() method. When a document is inserted a special key, "_id", is automatically added if the document does not already contain an "_id" key. The value of "_id" must be unique across the collection. insert() returns the value of "_id" for the inserted document.

The find_one() method returns a single document matching a query (or none if there are no matches). It is useful when you know there is only one matching document. Here find_one() method is used to get the first document from the students collection :

You can also find a student by its _id, which in our example is an ObjectId.

Multiple documents Query

To get more than one document as the result of a query we use the find() method. find() returns a cursor instance, which allows us to iterate over all matching documents. For example, we can iterate over every document in the students collection :