1024programmer Java Detailed explanation of methods for operating MongoDB in Python3, such as adding books, modifying queries, etc.

Detailed explanation of methods for operating MongoDB in Python3, such as adding books, modifying queries, etc.

MongoDB is a non-relational database written in C++ language. It is an open source database system based on distributed file storage. Its content storage format is similar to JSON objects. Its field values ​​​​can include other documents, arrays and document arrays, which is very flexible.

In this section, we will take a look at the storage operations of MongoDB under Python 3.

1. Preparation

Before you begin, please ensure that MongoDB has been installed and its service has been started, and that the Python PyMongo library has been installed.

2. Connect to MongoDB

When connecting to MongoDB, we need to use the MongoClient in the PyMongo library. Generally speaking, just pass in the IP and port of MongoDB, where the first parameter is the address host, and the second parameter is the port (if no parameters are passed to it, the default is 27017):

 importpymongo
 client = pymongo.MongoClient(host='localhost', port=27017)

In this way, you can create a MongoDB connection object.

In addition, the first parameter host of MongoClient can also be directly passed in the MongoDB connection string, which starts with mongodb, for example:

 client = MongoClient('mongodb://localhost:27017/')

This can also achieve the same connection effect.

3. Specify database

Multiple databases can be created in MongoDB. Next we need to specify which database to operate. Here we take the test database as an example to illustrate. The next step is to specify the database to be used in the program:

 db = client.test

Call the client’s test attribute here to return the test database. Of course, we can also specify it like this:

 db = client['test']

These two methods are equivalent.

4. Specify collection

Each database in MongoDB contains many collections, which are similar to tables in relational databases.

The next step is to specify the collection to be operated. Here, specify a collection name as students. Similar to specifying a database, there are two ways to specify a collection:

 collection = db.studentscollection = db['students']

In this way we declare a Collection object.

5. Insert data

Next, you can insert data. For the students collection, create a new piece of student data, which is represented in dictionary form:

 student = {
  'id': '20170101',
  'name': 'Jordan',
  'age': 20,
  'gender': 'male'
 }

The student’s student number, name, age and gender are specified here. Next, directly call the insert() method of the collection to insert data. The code is as follows:

 result = collection.insert(student)
 print(result)

In MongoDB, each piece of data actually has an _id attribute to uniquely identify it. If this attribute is not explicitly specified, MongoDB will automatically generate an _id attribute of type ObjectId. The insert() method will return the _id value after execution.

The running results are as follows:

 5932a68615c2606814c91f3d

Of course, we can also insert multiple pieces of data at the same time, just pass it in list form, the example is as follows:

 student1 = {
  'id': '20170101',
  'name': 'Jordan',
  'age': 20,
  'gender': 'male'
 }
 student2 = {
  'id': '20170202',
  'name': 'Mike',
  'age': 21,
  'gender': 'male'
 }
 result = collection.insert([student1, student2])
 print(result)

The return result is a collection of corresponding _ids:

 [ObjectId('5932a80115c2606a59e8a048'), ObjectId('5932a80115c2606a59e8a049')]

In fact, in PyMongo 3.x version, the insert() method is officially deprecated. Of course, there is nothing wrong with continuing to use it. It is officially recommended to use the insert_one() and insert_many() methods to insert a single record and multiple records respectively. The examples are as follows:

 student = {
  'id': '20170101',
  'name': 'Jordan',
  'age': 20,
  'gender': 'male'
 }
 result = collection.insert_one(student)
 print(result)
 print(result.inserted_id)

The running results are as follows:

 

 5932ab0f15c2606f0c1cf6c5

Different from the insert() method, this time it returns an InsertOneResult object, and we can call its inserted_id attribute to get the _id.

For the insert_many() method, we can pass the data in list form, the example is as follows:

 student1 = {
  'id': '20170101',
  'name': 'Jordan',
  'age': 20,
  'gender': 'male'
 }
 student2 = {
  'id': '20170202',
  'name': 'Mike',
  'age': 21,
  'gender': 'male'
 }
 result = collection.insert_many([student1, student2])
 print(result)
 print(result.inserted_ids)

The running results are as follows:

 
 [ObjectId('5932abf415c2607083d3b2ac'), ObjectId('5932abf415c2607083d3b2ad')]

The type returned by this method is InsertManyResult. You can get the _id list of inserted data by calling the inserted_ids attribute.

6. Query

After inserting data, we can use the find_one() or find() method to query, where fin�Data for a certain condition:

 count = collection.find({'age': 20}).count()
 print(count)

The operation result is a numerical value, that is, the number of data items that meet the conditions.

8. Sorting

When sorting, just call the sort() method directly and pass in the sorted fields and ascending and descending order flags. An example is as follows:

 results = collection.find().sort('name', pymongo.ASCENDING)

 print([result['name'] for result in results])

The running results are as follows:

 ['Harden', 'Jordan', 'Kevin', 'Mark', 'Mike']

Here we call pymongo.ASCENDING to specify ascending order. If you want to sort in descending order, you can pass in pymongo.DESCENDING.

9. Offset

In some cases, we may want to take only certain elements. In this case, we can use the skip() method to offset a few positions, such as offset 2, ignore the first two elements, and get the third and Later elements:

 results = collection.find().sort('name', pymongo.ASCENDING).skip(2)

 print([result['name'] for result in results])

The running results are as follows:

 ['Kevin', 'Mark', 'Mike']

In addition, you can also use the limit() method to specify the number of results to be fetched. The example is as follows:

 results = collection.find().sort('name', pymongo.ASCENDING).skip(2).limit(2)

 print([result['name'] for result in results])

The running results are as follows:

 ['Kevin', 'Mark']

If the limit() method is not used, three results will be returned originally. After adding the limit, two results will be intercepted and returned.

It is worth noting that when the number of databases is very large, such as tens of millions or billions, it is best not to use large offsets to query data, because this is likely to cause memory overflow. At this time, you can use operations similar to the following to query:

 from bson.objectid import ObjectId

 collection.find({'_id': {'$gt': ObjectId('593278c815c2602678bb2b8d')}})

At this time, you need to record the _id of the last query.

10. Update

For data update, we can use the update() method to specify the update conditions and updated data. For example:

 cOndition= {'name': 'Kevin'}
 student = collection.find_one(condition)
 student['age'] = 25
 result = collection.update(condition, student)
 print(result)

Here we want to update the age of the data named Kevin: first specify the query conditions, and then query the data. After modifying the age, call the update() method to pass in the original conditions and modified data.

The running results are as follows:

 {'ok': 1, 'nModified': 1, 'n': 1, 'updatedExisting': True}

The return result is in the form of a dictionary, ok represents successful execution, and nModified represents the number of affected data items.

In addition, we can also use the $set operator to update the data, the code is as follows:

 result = collection.update(condition, {'$set': student})

This will update only the fields that exist in the student dictionary. If there are other fields originally, they will not be updated or deleted. If $set is not used, all previous data will be replaced with the student dictionary; if other fields originally exist, they will be deleted.

In addition, the update() method is actually not officially recommended. It is also divided into update_one() method and update_many() method. The usage is more strict. Their second parameter needs to use the $ type operator as the key name of the dictionary. The example is as follows:

 cOndition= {'name': 'Kevin'}
 student = collection.find_one(condition)
 student['age'] = 26
 result = collection.update_one(condition, {'$set': student})
 print(result)
 print(result.matched_count, result.modified_count)

The update_one() method is called here. The second parameter can no longer be passed directly into the modified dictionary. Instead, it needs to use the form {‘$set’: student}, and the return result is of type UpdateResult. Then call the matched_count and modified_count attributes respectively to get the number of matching data and the number of affected data.

The running results are as follows:

 
 1 0

Let’s look at another example:

 cOndition= {'age': {'$gt': 20}}
 result = collection.update_one(condition, {'$inc': {'age': 1}})
 print(result)
 print(result.matched_count, result.modified_count)

The query condition specified here is that age is greater than 20, and then the update condition is {‘$inc’: {‘age’: 1}}, that is, the age is increased by 1. After execution, the age of the first data that meets the condition will be increased. 1.

The running results are as follows:

 
 1 1

You can see that the number of matching items is 1, and the number of affected items is also 1. If the update_many() method is called, all data that meets the conditions will be updated. The example is as follows:

 cOndition= {'age': {'$gt': 20}}
 result = collection.update_many(condition, {'$inc': {'age': 1}})
 print(result)
 print(result.matched_count, result.modified_count)

At this time, the number of matches is no longer 1, and the running results are as follows:

 
 3 3

As you can see, all matching data will be updated at this time.

11. Delete

The deletion operation is relatively simple. Just call the remove() method to specify the conditions for deletion. At this time, all data that meets the conditions will be deleted. An example is as follows:

 result = collection.remove({'name': 'Kevin'})
 print(result)

The running results are as follows:

 {'ok': 1, 'n': 1}

In addition, there are still two new recommended methods-delete_one() and delete_many(). An example is as follows:

 result = collection.delete_one({'name': 'Kevin'})
 print(result)
 print(result.deleted_count)
 result = collection.delete_many({'age': {'$lt': 25}})
 print(result.deleted_count)

The running results are as follows:

 
 1
 4

delete_one() deletes the first data that meets the conditions, and delete_many() deletes all data that meets the conditions. Their return results are all of type DeleteResult, and you can call the deleted_count attribute to get the number of deleted data items.

12. Other operations

In addition, PyMongo also provides some combination methods, such as find_one_and_delete(), find_one_and_replace() and find_one_and_update(), which are delete, replace and update operations after search. Their usage is basically the same as the above method.

In addition, you can also operate on the index. Related methods include create_index(), create_indexes(), drop_index(), etc.

For detailed usage of PyMongo, please refer to the official documentation:

http://api.mongodb.com/python/current/api/pymongo/collection.html.

In addition, there are some operations on the database and the collection itself, which will not be explained one by one here. You can refer to the official documentation: http://api.mongodb.com/python/current/api/pymongo/.

This section explains how to use PyMongo to operate MongoDB to add, delete, modify and query data.

For more articles on how to add and modify MongoDB, you can check out the relevant links below

At this time, the number of matches is no longer 1, and the running results are as follows:

 
 3 3

As you can see, all matching data will be updated at this time.

11. Delete

The deletion operation is relatively simple. Just call the remove() method to specify the conditions for deletion. At this time, all data that meets the conditions will be deleted. An example is as follows:

 result = collection.remove({'name': 'Kevin'})
 print(result)

The running results are as follows:

 {'ok': 1, 'n': 1}

In addition, there are still two new recommended methods-delete_one() and delete_many(). An example is as follows:

 result = collection.delete_one({'name': 'Kevin'})
 print(result)
 print(result.deleted_count)
 result = collection.delete_many({'age': {'$lt': 25}})
 print(result.deleted_count)

The running results are as follows:

 
 1
 4

delete_one() deletes the first data that meets the conditions, and delete_many() deletes all data that meets the conditions. Their return results are all of type DeleteResult, and you can call the deleted_count attribute to get the number of deleted data items.

12. Other operations

In addition, PyMongo also provides some combination methods, such as find_one_and_delete(), find_one_and_replace() and find_one_and_update(), which are delete, replace and update operations after search. Their usage is basically the same as the above method.

In addition, you can also operate on the index. Related methods include create_index(), create_indexes(), drop_index(), etc.

For detailed usage of PyMongo, please refer to the official documentation:

http://api.mongodb.com/python/current/api/pymongo/collection.html.

In addition, there are some operations on the database and the collection itself, which will not be explained one by one here. You can refer to the official documentation: http://api.mongodb.com/python/current/api/pymongo/.

This section explains how to use PyMongo to operate MongoDB to add, delete, modify and query data.

For more articles on how to add and modify MongoDB, you can check out the relevant links below

This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/detailed-explanation-of-methods-for-operating-mongodb-in-python3-such-as-adding-books-modifying-queries-etc/

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索