Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.
MongoDB is an open source, distributed and document-oriented non-relational database. It has the advantages of high performance, high availability, easy to expand, and supports a rich query language to support read and write operations and more complex queries.
Let’s take a look at using Python to manipulate the MongoDB database.
Connect the mongo
To connect to and operate MongoDB, use the Python third-party library PyMongo, which can be installed using PIP Install Pymongo. You can use the following code to create a MongoDB connection object.
import pymongo
client = pymongo.MongoClient(host='localhost', port=27017)
Copy the code
Generally, you pass in two arguments, the first to address host (localhost by default) and the second to port (27017 by default). Alternatively, the host argument is passed directly to MongoDB’s connection string, for example:
client = pymongo.MongoClient('mongodb://localhost:27017')
Copy the code
Specify (switch) the database
db = client.test
# or
# db = client['test']
Copy the code
If the database does not exist, it is automatically created; otherwise, switch to the specified database. Note: The newly created database is not visible in the visualization tool until data is inserted.
Specify (switch) collections
The MongoDB database contains many collections, similar to tables in a relational database. Similarly, we can specify collections to operate on in the same way as we can specify databases.
collection = db.users
# or
collection = db['users']
Copy the code
Insert data
Call the insert_one() method of collection to insert a single piece of data.
user = {
'name': 'tigeriaf'.'gender': 'male'.'age': 24
}
collection.insert_one(user)
Copy the code
In MongoDB, each piece of data has a unique _ID attribute. If no _id is explicitly specified, MongoDB automatically generates an _ID attribute of the ObjectId type.
Of course, we can also insert multiple pieces of data, using the insert_many() method, which passes the data 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)
Copy the code
Query data
Data is queried by find_one() or find() methods, where find_one() returns a single result and find() returns multiple results.
result = collection.find_one({'name': 'tigeriaf'})
print(type(result), result)
Copy the code
Select * from tigeriaf where name = tigeriaf;
<class 'dict'> {'_id': ObjectId('614be85f1cc0a98d6f034de7'), 'name': 'tigeriaf'.'gender': 'male'}
Copy the code
For multiple queries, we can use the find() method, for example, here to find data age 20, as shown in the following example:
results = collection.find({'gender': "male"})
print(results)
for result in results:
print(result)
Copy the code
The running results are as follows:
<pymongo.cursor.Cursor object at 0x0BDF8210>
{'_id': ObjectId('614be85f1cc0a98d6f034de7'), 'name': 'tigeriaf'.'gender': 'male'}
{'_id': ObjectId('614beb3ad0f17d253e2ef81c'), 'name': 'zhangsan'.'gender': 'male'}
{'_id': ObjectId('614beb3ad0f17d253e2ef81d'), 'name': 'lisi'.'gender': 'male'}
Copy the code
The return result is of type Cursor, so we can go over and get all the results.
Mongo support more complex queries, of course, such as more enquiry, regular expressions, detail view mongo docs.mongodb.com/manual/refe official document…
Statistical query
You can call the count() method to count the number of results of a query.
count = collection.find({'gender': "male"}).count()
print(count)
Copy the code
Results the sorting
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)
Copy the code
The running results are as follows:
{'_id': ObjectId('614bf7fca5af6d1d46df0878'), 'name': 'lisi'.'gender': 'male'.'age': 24}
{'_id': ObjectId('614bf72ab1b973eae1b32fee'), 'name': 'tigeriaf'.'gender': 'male'.'age': 24}
{'_id': ObjectId('614bf7fca5af6d1d46df0879'), 'name': 'wangwu'.'gender': 'female'.'age': 24}
{'_id': ObjectId('614bf7fca5af6d1d46df0877'), 'name': 'zhangsan'.'gender': 'male'.'age': 25}
Copy the code
The offset
In some cases, we may only want to obtain certain data, so skip() can be used for offset operation. For example, skip(2) can ignore the first two data and get the data after the third one.
results = collection.find().sort('name', pymongo.ASCENDING).skip(2)
for result in results:
print(result)
Copy the code
The running results are as follows:
{'_id': ObjectId('614bf7fca5af6d1d46df0879'), 'name': 'wangwu'.'gender': 'female'.'age': 24}
{'_id': ObjectId('614bf7fca5af6d1d46df0877'), 'name': 'zhangsan'.'gender': 'male'.'age': 25}
Copy the code
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)
Copy the code
The running results are as follows:
{'_id': ObjectId('614bf72ab1b973eae1b32fee'), 'name': 'tigeriaf'.'gender': 'male'.'age': 24}
{'_id': ObjectId('614bf7fca5af6d1d46df0879'), 'name': 'wangwu'.'gender': 'female'.'age': 24}
Copy the code
Update the data
Data can be updated using the update_one() and update_many() methods, with the update_one() method updating one data and the update_many() method updating multiple data.
condition = {'name': 'wangwu'}
user = collection.find_one(condition)
user['age'] + =1
result = collection.update_one(condition, {'$set': user})
print(result)
print(result.matched_count, result.modified_count)
Copy the code
Here, the update_one() method is called to modify the data whose name is wangwu. The second argument requires the $type operator as the dictionary’s key name. The result is that the matched_count and modified_count properties are called to get the number of matched data items and the number of affected data items.
The running results are as follows:
<pymongo.results.UpdateResult object at 0x0C96E738>
1 1
Copy the code
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)
Copy the code
$inc: {‘age’: 1}} age + 1
<pymongo.results.UpdateResult object at 0x0CB628A0>
2 2
Copy the code
You can see that multiple pieces of data are updated.
Delete the data
You can use the delete_one() and delete_many() methods to delete data, the delete_one() method to delete one data, and the delete_many() method to delete multiple data.
result = collection.delete_one({'name': 'zhangsan'})
print(result.deleted_count)
result = collection.delete_many({'gender': "male"})
print(result.deleted_count)
Copy the code
The running results are as follows:
1
2
Copy the code
Delete_one () deletes the first data that meets the condition, and delete_many() deletes all data that meets the condition.
conclusion
There are other operations on databases, collections and data, which are not explained in detail here, but can be viewed in the official documentation.
Finally, thank my girlfriend for her tolerance, understanding and support in work and life!