MongoDB is a document-type database developed using C ++, and PyMongo is the Python driver of MongoDB. Install by pip $ [sudo] pipinstallpymongo if you want to install a specific version: $ [sudo] pipinstallpymongo2.6.3 Install through source code $ gitclonegit: github. commongodbmongo-pyt
MongoDB is a document-type database developed using C ++, and PyMongo is the Python driver of MongoDB. Install and use pip to install $ [sudo] pip install pymongo if you want to install a specific version: $ [sudo] pip install pymongo = 2.6.3 install through source code $ git clone git: // github.com/mongodb/mongo-pyt
MongoDB is a document-type database developed using C ++, and PyMongo is the Python driver of MongoDB.
Install using pip
$ [sudo] pip install pymongo
To install a specific version:
$ [sudo] pip install pymongo==2.6.3
Install with source code
$ git clone git://github.com/mongodb/mongo-python-driver.git pymongo$ cd pymongo/$ [sudo] python setup.py install
Note: Using C extension will help improve performance. However, if you receive a warning in uwsgi, you can choose to install only the python driver without the C extension.
$ [sudo] python setup.py --no_ext install
Note: If you are using Python3, PyMongo only supports Python 3.1 and later versions.
Use
Start the mongodb server first:
$ mongod
Connect to the server
Then run the python program to connect to the server:
from pymongo import MongoClientclient = MongoClient()
The above will be connected to the default host and port (localhost: 27017), you can also specify the host name and port:
client = MongoClient('localhost', 27017)
Or:
client = MongoClient('mongodb://localhost:27017/')
Access Database
db = client.test_database
If the database name cannot be accessed directly using the attribute name style, you need to use the dictionary style:
db = client['test-database']
Access Data Set
Similar to accessing a database:
collection = db.test_collectioncollection = db['test-collection']
Insert data
In MongoDB, data is saved in JSON-like format, while in PyMongo, data is in dictionary style. Then, you can insert data using the insert () method of the data set object.
import datetimepost = {"author": "Mike", "text": "My first blog post!", "tags": ["mongodb", "python", "pymongo"], "date": datetime.datetime.utcnow()}post_id = db.posts.insert(post)
Query data
You can use the find () method of the data set object to query data.
db.posts.find({"author": "Mike"})db.posts.find_one({"author": "Mike"})
Original article address: pymongo tutorial (1) -- Overview, thanks to the original author for sharing.