In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-09 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article is to share with you the content of a sample analysis of Python manipulation of MongoDB. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
1. Connect MongoDB
You need to use the Python third-party library pymongo to connect and operate MongoDB, and you can install it using pip install pymongo. You can use the following code to create a connection object for MongoDB.
Import pymongoclient = pymongo.MongoClient (host='localhost', port=27017)
Generally speaking, you can pass in two parameters, the first of which is address host (default is localhost), and the second parameter is port port (default is 27017).
Another way is to pass the host parameter directly into the connection string of MongoDB, for example:
Client = pymongo.MongoClient ('mongodb://localhost:27017') 2, specify (switch) database db = client.test# or # db = client [' test']
If the database does not exist, it is created automatically, otherwise, switch to the specified database. Note: the newly created database cannot be seen in the visualization tool until the data is inserted.
3. Specify (switch) the collection
MongoDB's database contains many collections collection, similar to tables in a relational database, and again, we can specify the collections to operate on in a manner similar to the specified database below.
Collection = db.users# or collection = db ['users'] 4, insert data
You can insert a single piece of data by calling the insert_one () method of collection.
User = {'name':' tigeriaf', 'gender':' male', 'age': 24} collection.insert_one (user)
In MongoDB, each piece of data has a unique _ id attribute, and if it is not explicitly specified, _ id,MongoDB will automatically generate a _ id attribute of type ObjectId.
Of course, we can also insert multiple pieces of data, using the insert_many () method, and the data is passed as a list.
User_list = [{'name':' zhangsan', 'gender':' male', 'age': 25}, {' name': 'lisi',' gender': 'male',' age': 24}, {'name':' wangwu', 'gender':' female' 'age': 24}] collection.insert_many (user_list)
5. Query data
Query the data through the find_one () or find () method, where the find_one () query returns a single result and find () returns multiple results.
Result = collection.find_one ({'name':' tigeriaf'}) print (type (result), result)
We query the data whose name is tigeriaf, and the returned result is a dictionary type. The running result is as follows:
{'_ id': ObjectId ('614be85f1cc0a98d6f034de7'),' name': 'tigeriaf',' gender': 'male'}
For queries with multiple pieces of data, we can use the find () method, for example, to find data with the age of 20 here. The example is as follows:
Results = collection.find ({'gender': "male"}) print (results) for result in results: print (result)
The running results are as follows:
{'_ id': ObjectId ('614be85f1cc0a98d6f034de7'),' name': 'tigeriaf',' gender': 'male'}
{'_ id': ObjectId ('614beb3ad0f17d253e2ef81c'),' name': 'zhangsan',' gender': 'male'}
{'_ id': ObjectId ('614beb3ad0f17d253e2ef81d'),' name': 'lisi',' gender': 'male'}
The returned result is of type Cursor, and we can traverse to get all the results.
6. Statistical inquiry
You can call the count () method to count the number of query results.
Count = collection.find ({'gender': "male"}) .count () print (count) 7, sort the results
You can call the sort () method to sort the data of the query.
Results = collection.find () .sort ('name', pymongo.ASCENDING) for result in results: print (result)
The running results are as follows:
{'_ id': ObjectId ('614bf7fca5af6d1d46df0878'),' name': 'lisi',' gender': 'male',' age': 24}
{'_ id': ObjectId ('614bf72ab1b973eae1b32 age':'), 'name':' tigeriaf', 'gender':' male', 'age': 24}
{'_ id': ObjectId ('614bf7fca5af6d1d46df0879'),' name': 'wangwu',' gender': 'female',' age': 24}
{'_ id': ObjectId ('614bf7fca5af6d1d46df0877'),' name': 'zhangsan',' gender': 'male',' age': 25}
8. Offset
In some cases, we may only want to get a few pieces of data, we can use the skip () method for migration operations, such as skip (2), ignore the first two pieces of data and get the data after the third.
Results = collection.find () .sort ('name', pymongo.ASCENDING) .skip (2) for result in results: print (result)
The running results are as follows:
{'_ id': ObjectId ('614bf7fca5af6d1d46df0879'),' name': 'wangwu',' gender': 'female',' age': 24}
{'_ id': ObjectId ('614bf7fca5af6d1d46df0877'),' name': 'zhangsan',' gender': 'male',' age': 25}
You can also use the limit () method to limit the number of results.
Results = collection.find (). Sort ('name', pymongo.ASCENDING) .skip (1) .limit (2) for result in results: print (result)
The running results are as follows:
{'_ id': ObjectId ('614bf72ab1b973eae1b32 age':'), 'name':' tigeriaf', 'gender':' male', 'age': 24}
{'_ id': ObjectId ('614bf7fca5af6d1d46df0879'),' name': 'wangwu',' gender': 'female',' age': 24}
9. Update data
You can update the data using the update_one () method and the update_many () method, the update_one () method updates one piece of data, and the update_many () method updates multiple pieces of data.
Condition = {'name':' wangwu'} user = collection.find_one (condition) user ['age'] + = 1result = collection.update_one (condition, {' $set': user}) print (result) print (result.matched_count, result.modified_count)
Here, the update_one () method is called to modify the data whose name is wangwu. The second parameter needs to use the $type operator as the key name of the dictionary. The result is returned by calling the matched_count and modified_count properties to get the matching number of data and the number of affected data.
The running results are as follows:
1 1
Calling the update_many () method updates all eligible data.
Condition = {'age': 24} result = collection.update_many (condition, {' $inc': {'age': 1}}) print (result) print (result.matched_count, result.modified_count)
The above code specifies that the query condition is age equal to 24, and then the update condition is {'$inc': {'age': 1}}, that is, age plus 1.
2 2
You can see that multiple pieces of data have been updated.
10. Delete data
You can delete data using the delete_one () method and the delete_many () method, the delete_one () method deletes a piece of data, and the delete_many () method deletes multiple pieces of data.
Result = collection.delete_one ({'name':' zhangsan'}) print (result.deleted_count) result = collection.delete_many ({'gender': "male"}) print (result.deleted_count)
The running results are as follows:
one
two
Delete_one () deletes the first eligible data, and delete_many () deletes all eligible data.
Thank you for reading! This is the end of this article on "sample Analysis of Python Operation MongoDB". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it out for more people to see!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.