Detailed description of Python3 simple and easy-to-understand Mongodb tutorial, detailed description of python3mongodb
Connect to database
To connect to a database, you must provide an address and interface. First, import the package.
from pymongo import MongoClientconn = MongoClient('localhost',27017)
Of course, you can write as follows:
conn = MongoClient('mongodb://localhost:27017/')
Create a database
Mongodb does not need to create a database in advance, but is directly used. If it is not found, it is automatically created.
db = conn.testdb
The preceding statement creates a database named testdb. However, when no data is inserted, you cannot see the database in the management tool (not displayed ).
Insert data
First, insert a piece of data.
Insert a single record
From pymongo import Export clientconn = MongoClient ('mongodb: // localhost: 27017/') db = conn. testdbdb. col. insert ({"name": 'anying', 'vince ': 'jiangsu', 'age': 25 })
Note: In the following operations, the database connection operation will be ignored and the core code will be directly written. Please complete the operation yourself.
The python Console does not happen, which means success. Using management tools to view database records does contain a piece of data.
Insert multiple records
Mongodb can also insert multiple data records at a time.
Db. col. insert ([{"name": 'anying', 'province ': 'jiangsu', 'age': 25}, {"name": 'zhang san', 'province ': 'zhejiang ', 'age': 24}, {"name": 'zhang San 1', 'vince': 'zhejiang 1', 'age': 25 }, {"name": 'zhang San 2', 'province ': 'zhejiang 2', 'age': 26 },{ "name": 'zhang San 3', 'province ': 'zhejiang 3', 'age': 28},])
Query data
Next we will query the inserted data.
Single Query
We can use find_one () to query a record.
db.col.find_one()
The preceding statement can query a mongodb record. The _ id in the record is the unique value automatically generated by Mongodb.
Copy codeThe Code is as follows:
{'_ Id': ObjectId ('5925351ad92fac3250b9ae3f'), 'name': 'anying', 'province': 'jiangsu ', 'age': 25}
We can insert some data for the following operations. (Omitted tens of thousands of characters)
Query all
If we need to query all records, we can use db. col. find () but we can find a result resource set.
We can use for to list all records.
for item in db.col.find(): print(item)
In this way, all records can be obtained.
{'_ Id': ObjectId ('5925351ad92fac3250b9ae3f'), 'name': 'anying', 'province': 'jiangsu ', 'age ': 25} {'_ id': ObjectId ('592550e5d92fac0b8c449f87'), 'name': 'hangsan ', 'province': 'beijing', 'age ': 29} {'_ id': ObjectId ('592550f6d92fac3548c20b1a'), 'name': 'lisi', 'province ': 'shanghai', 'age ': 22} {'_ id': ObjectId ('59253478d92fac43dcb%a'), 'name': 'wang binm', 'province': 'guangdong ', 'age': 30}
Conditional Query
You can filter data by inserting the query conditions as parameters.
for item in db.col.find({'name':"yanying"}): print(item)
Query Result
Copy codeThe Code is as follows:
{'_ Id': ObjectId ('5925351ad92fac3250b9ae3f'), 'name': 'anying', 'province': 'jiangsu ', 'age': 25}
Of course, you can also query records smaller than a specific value.
for item in db.col.find({"age":{"$lt":25}}): print(item)
Or a record greater than a specific value
for item in db.col.find({"age":{"$gt":25}}): print(item)
Statistics Query
The above code can calculate the number of all records
db.col.find().count() // 4
Or add some conditions.
db.col.find({"age":{"$gt":25}}).count() //2
Query records by _ id
_ Id is the id automatically generated by mongodb. Its type is ObjectId. to use it, you need to convert the type.
This method is provided in python3, but a library needs to be imported.
from bson.objectid import ObjectId
In this way, you can directly use _ id for query.
collection.find_one({'_id':ObjectId('592550e5d92fac0b8c449f87')})
Result sorting
You only need to put the fields to be sorted into the sort method. Mongodb is in ascending order by default.
db.col.find().sort("age")
However, you can add some parameters to change the sorting method. For example, in reverse order, remember to import the pymongo Library first.
import pymongodb.col.find().sort("UserName",pymongo.DESCENDING)
You can also sort it in ascending order, though this is the default case.
for item in db.col.find().sort('age',pymongo.ASCENDING): print(item)
Update Data
Updating data is simple. You only need one condition and the data to be updated.
Copy codeThe Code is as follows:
Db. col. update ({'_ id': ObjectId ('59253478d92fac43dcb5oa') },{' $ set': {'name': 'wang Erma 100 '}})
The result is as follows:
Copy codeThe Code is as follows:
{'_ Id': ObjectId ('59253478d92fac43dcb%a'), 'name': 'wang Erma 100', 'province': 'guangdong ', 'age': 30}
Delete data
To delete data, use the remove () method. If the method has conditions, delete the specified conditions. Otherwise, delete all
Delete the user whose name is Wang Erma 33333.
Db. col. remove ({'name': 'wang Erma 33333 '})
Delete all data (use with caution)
db.col.remove()
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.