Python Driver in Mongo DB


Python Driver in Mongo DB

The PyMongo distribution contains tools for interacting with the MongoDB database from Python. This tutorial covers installing PyMongo on various operating systems, connections, and basic database operations 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.

Setuptools provides download, build, install, upgrade, and uninstall Python packages.

Working with MongoDB and PyMongo

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.

Getting a Database

A single instance of MongoDB can support multiple independent databases. 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.

Find a 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 student's collection.

Find a specific document

find_one() method also supports querying on particular elements that the resulting document must match.

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.