Python MongoDB
MongoDB is one of the most popular NoSQL databases currently, using the BSON data type (similar to JSON).
For MongoDB database installation and introduction, you can check ourMongoDB Tutorial.
PyMongo
To connect Python to MongoDB, you need a MongoDB driver. Here we use the PyMongo driver to connect.
pip Installation
pip is a general-purpose Python package management tool that provides functions for searching, downloading, installing, and uninstalling Python packages.
Install pymongo:
$ python3 -m pip3 install pymongo
You can also specify the version to install:
$ python3 -m pip3 install pymongo==3.5.1
Update pymongo command:
$ python3 -m pip3 install --upgrade pymongo
easy_install Installation
Older versions of Python can use easy_install to install, easy_install is also a Python package management tool.
$ python -m easy_install pymongo
Update pymongo command:
$ python -m easy_install -U pymongo
Test PyMongo
Next, we can create a test file demo_test_mongodb.py, with the following code:
demo_test_mongodb.py file code:
Execute the above code file. If no error occurs, the installation is successful.
Create Database
Create a Database
To create a database, you need to use the MongoClient object and specify the URL address of the connection and the name of the database to be created.
In the following example, we create the database exampledb:
Example
Note:In MongoDB, a database is only created after content is inserted! That is to say, after creating a database, you must create a collection (data table) and insert a document (record) before the database is actually created.
Determine if the database already exists
We can read all databases in MongoDB and determine whether the specified database exists:
Example
Note:database_names is deprecated in the latest version of Python. After Python 3.7+, it was changed to list_database_names().
Create Collection
Collections in MongoDB are similar to tables in SQL.
Create a Collection
MongoDB uses database objects to create collections, as shown in the example below:
Example
Note:In MongoDB, a collection is only created after content is inserted! That is to say, after creating a collection (data table), you must insert a document (record) before the collection is actually created.
Determine if the collection already exists
We can read all collections in the MongoDB database and determine whether the specified collection exists:
Example
Note:collection_names is deprecated in the latest version of Python. After Python 3.7+, it was changed to list_collection_names().
Operations such as add, delete, update, and query
The following table lists more MongoDB operations. Click on the specific link for details:
| Serial number | Function |
|---|---|
| 1 | Add data |
| 2 | Query data |
| 3 | Modify data |
| 4 | Data sorting |
| 5 | Delete data |