MongoDB can store JSON data compared to traditional relational databases, which is perfect for storing JSON data returned by data crawling. Previously, we introduced the installation of MongoDB on Windows, today we mainly learn to connect to MongoDB using Python and perform the operation of adding, deleting, and checking.
Before connecting to MongoDB, the first thing you need to install is the Python package: PyMongo, which is very easy to install. Just execute pip install pymongo and you are done.
Creating connections
After installing PyMongo, connecting to MongoDB using Python becomes exceptionally easy. The specific way is.
Or use the following.
If the connection contains an account password, etc., please refer to: pymongo.mongo_client.MongoClient
Connecting to the database
The operation of connecting to the database is also very simple. The most important thing is that you don’t need to create a database before you connect to it, if the database exists then you connect directly, if the database doesn’t exist then a new library will be created. The specific way is.
Either of the above two ways is sufficient.
Collection concept
There is a concept of Collection in MongoDB.I understand it as a namespace, similar to the concept of Scheme in other databases, Collection can be understood as a collection of tables.Collection can be used or not, depending on whether you want to classify the tables under the library. Related operations.
It is important to know that the collection is created when the first table is created.
Inserting Data
Where the way to insert data is very simple, the longest used method is, insert_one () and insert_many () method, literally you can see that one is to insert a data, the other is to insert multiple data, example.
|
|
Querying data
As with inserting data, querying data provides methods to query one or more pieces of data, the methods are find_one() and find() respectively. Example.
In addition, when querying multiple items, you can set the number returned or other qualifications: pymongo.collection.Collection.find
In addition conditions that need to support similar WHERE conditions in relational databases, you need to use specific keywords. Example.
Deleting data
Deleting data is also very simple, the main methods used are: delete_one() and delete_many().
Updating data
The main methods for updating data are, update_one() and update_many() In addition, there is a replace_one() method is used to replace, as not much is used, see the documentation.
Creating indexes
pyMongo also supports create index, which can further improve the performance of queries, example.
Reference link.