Catalog : The basic chapter ( Can solve the problem of 80 The problem of )
01 MongoDB Overview 、 Application scenarios 、 Download mode 、 Connection mode and development history, etc
02 MongoDB data type 、 Key concepts and shell Commonly used instructions
03 MongoDB Various additions to documents 、 to update 、 Delete operation summary
04 MongoDB Various query operations And summary of aggregation operations
05 MongoDB Summarize the various operations of the column
python3 operation MongoDB Various cases of
# -*- encoding: utf-8 -*-
import time
import pymongo
import datetime
# Create objects
client = pymongo.MongoClient('mongodb:// account number : password @ host : Port number /?authSource=admin')
# Connect DB database
db = client[' Database name ']
def insert_one():
# Connect sets user, Collections are similar to data tables in a relational database ; If the set doesn't exist , A new set will be created user
user_collection = db.user_demo
# Format the document ( Documents are what we often call data )
user_info = {
"_id": 105,
"author": " Little green ",
"text": "Python Development ",
"tags": ["mongodb", "pymongo"],
"date": datetime.datetime.now()}
# Use insert_one Add a single document ,inserted_id Gets the value after writing id
# When adding a document , If the document does not already contain "_id" key , Will automatically add "_id"."_id" The value of must be unique in the collection
# inserted_id Used to get the added id, If you don't need , You can get rid of
user_id = user_collection.insert_one(user_info).inserted_id
print("user id is ", user_id)
def insert_many():
# Batch addition
user_infos = [{
"_id": 101,
"author": " Xiao Huang ",
"text": "Python Development ",
"tags": ["mongodb", "python", "pymongo"],
"date": datetime.datetime.utcnow()},
{
"_id": 102,
"author": " Xiao Huang _A",
"text": "Python Development _A",
"tags": {
"db":"Mongodb","lan":"Python","modle":"Pymongo"},
"date": datetime.datetime.utcnow()},
]
user_collection = db.user_insert_many
# inserted_ids Used to get the added id, If you don't need , It can be removed directly
user_id = user_collection.insert_many(user_infos).inserted_ids
print("user id is ", user_id)
def bulk_insert_data():
from pymongo import UpdateOne
data_list = [{
'user_id': 5, 'name': ' Zhang San 1', 'age': 27, 'email': '[email protected]'},
{
'user_id': 6, 'name': ' Li Si 1', 'age': 26, 'email': '[email protected]'},
{
'user_id': 7, 'name': ' Wang Wu 1', 'age': 29, 'email': '[email protected]'},
{
'user_id': 8, 'name': ' Zhao Liu 1', 'age': 26, 'email': '[email protected]'}]
bulk_data_list = []
for data in data_list:
one = UpdateOne({
"_id": data['user_id']}, {
"$set": {
"name": data['name'],
"age": data['age'],
"email": data['email'],
"date": datetime.datetime.now()}}, upsert=True)
bulk_data_list.append(one)
try:
collection_item = db.bulk_insert_demo
collection_item.bulk_write(bulk_data_list)
except Exception as e:
print(f'e: {
e}')
print(f"{
time.strftime('%Y-%m-%d %H:%M:%S')}, It has been saved mongo: {
len(bulk_data_list)} strip ")
if __name__ == '__main__':
# Insert a single piece of data
insert_one()
# Insert multiple data
# insert_many()
# Batch insert
# bulk_insert_data()
# -*- encoding: utf-8 -*-
import re
import pymongo
# Create objects
# client = pymongo.MongoClient()
client = pymongo.MongoClient('mongodb:// account number : password @ host : Port number /?authSource=admin')
# Connect DB database
db = client[' Database name ']
def find_by_condition():
# Connect sets user, Collections are similar to data tables in a relational database , If the set doesn't exist , A new set will be created user
user_collection = db.user
# 1. Query the document : find({"_id":101}), among {"_id":101} Is the query condition , If the query condition is empty , The default query is all
# find_value = user_collection.find({"_id": 103})
# print(list(find_value))
# 2. If you want to implement multi condition query ,$and and $or, How to use it is as follows :
# AND Conditions of the query
# find_value = user_collection.find({"$and": [{"_id": 104}, {"author": " Small blue "}]})
# print(list(find_value))
# OR Conditions of the query
# find_value = user_collection.find({"$or": [{"author": " Xiao Huang _A"}, {"author": " Xiao Huang "}]})
# print(list(find_value))
# 3. Find by range : $gt: Greater than , $gte: Greater than or equal to , $lt: Less than , $lte: Less than or equal to , $ne: It's not equal to ,
# Such as search id>102 And id<104(_id=101) Documents
# find_value = user_collection.find({"_id": {"$gt": 102, "$lt": 104}})
# print(list(find_value))
# lookup id stay [100,101] Documents
# find_value = user_collection.find({"_id": {"$in": [100, 101]}})
# print(list(find_value))
# find_value = user_collection.find({"and": [{"_id": {"$gt": 102, "$lt": 105}},
# {"_id": {"$in": [100, 105]}}]})
# print(list(find_value))
# 4. Fuzzy query is actually implemented by adding regular expressions
# # Method 1
# find_value = user_collection.find({"author": {"$regex": ".* Small .*"}})
# print(list(find_value))
# # Method 2
regex = re.compile(".* Small .*")
find_value = user_collection.find({
"author": regex})
print(list(find_value))
# 5. Query embedding / Nested documents
# Query field "tags":{"db":"Mongodb","lan":"Python","modle":"Pymongo"}
# Query nested fields , Just query a value in the nest
find_value = user_collection.find({
"tags.db": "Mongodb"})
print(list(find_value))
# 6. Query field "tags":{"db":
# {"Mongodb":"NoSql","MySql":"Sql"},"lan":"Python","modle":"Pymongo"}
# find_value = user_collection.find({"tags.db.Mongodb": "NoSql"})
# print(list(find_value))
def find_many():
user_collection = db.user
# 1. Query document quantity
# result_data = user_collection.count_documents({})
# print(result_data)
# 2. Limit the return result
# result_data_limit = user_collection.find({}).limit(2)
# for result in result_data_limit:
# print(result)
# 3. Sort query results : field value 1 Indicate positive order , -1 Reverse order
# user_collection = db.bulk_insert_demo
# result_data_sort = user_collection.find({'age': {'$gt': 22}}).sort([('age', -1)])
# print(list(result_data_sort))
# 4. De duplication of data
user_collection = db.bulk_insert_demo
# Yes age Field de duplication
result_data_distinct = user_collection.distinct('age')
print(list(result_data_distinct))
# To meet certain conditions age Field de duplication
# result_data_distinct = user_collection.distinct('age', {'age': {'$gte': 22}})
# print(list(result_data_distinct))
# 5. The offset
# results = collection.find().sort('id', pymongo.ASCENDING).skip(1)
# for result in results:
# print(result)
if __name__ == '__main__':
# Query documents according to criteria
# find_by_condition()
# Query data
find_many()
# -*- encoding: utf-8 -*-
import pymongo
# Create objects
client = pymongo.MongoClient('mongodb:// account number : password @ host : Port number /?authSource=admin')
# Connect DB database
db = client[' Database name ']
def update_one():
# update_one( filter , Update the content ), Filter criteria is empty , Update the first document by default
# If the query has multiple pieces of data , Update the first data in sequence
# {"author": " Small blue "}, {"$set": {"author": " Xiao Huang ", "text": " data mining "}}
user_collection = db.user
user_collection.update_one({
"author": " Small blue "}, {
"$set": {
"author": " Xiao Huang ", "text": " data mining "}})
def replace_one():
# replace_one( filter , Update the content ) Used to replace the entire piece of data
# If some data in the document is not updated , Just remove this part of the data
# topic_data.update_one({"_id": ObjectId(mongo_id)}, {"$set": {'tag_field': 0}})
user_collection = db.user
user_collection.replace_one({
"author": " Little green "},
{
"author": " Little green ", "text": "Python_django"})
def update_many():
# update_many( filter , Update the content ) Used to batch update documents , If the query has multiple pieces of data , All data will be updated
# topic_data.update_many({"tag_field": {"$exists": False}}, {"$set": {'tag_field': 0}})
user_collection = db.user
user_collection.update_many({
"author": " Xiao Huang "},
{
"$set": {
"text": "Python_web Development "}})
if __name__ == '__main__':
# Update a single document
# update_one()
# Replace a piece of data
replace_one()
# Update multiple data
# update_many()
# -*- encoding: utf-8 -*-
import pymongo
# Create objects
# client = pymongo.MongoClient()
client = pymongo.MongoClient('mongodb:// account number : password @ host : Port number /?authSource=admin')
# Connect DB database
db = client[' Database name ']
user_collection = db.user
def delete_one():
# Delete a single document
# delete_one( filter ), Filter criteria is empty , Delete the first document by default
user_collection.delete_one({
"_id": 100})
def delete_many():
# delete_many( filter ) Used to delete multiple pieces of data
user_collection.delete_many({
"author": " Xiao Huang "})
if __name__ == '__main__':
# Delete a single document
delete_one()
# Delete multiple data
# delete_many()
import pymongo
handler = pymongo.MongoClient().monog_db.example_user
rows = handler.aggregate([
{
'$lookup': {
'from': 'example_post',
'localField': 'id',
'foreignField': 'user_id',
'as': 'weibo_info'
}
},
{
'$unwind': '$weibo_info'},
{
'$project': {
'name': 1,
'work': 1,
'content': '$weibo_info.content',
'post_time': '$weibo_info.post_time'}}
])
for row in rows:
print(row)
️ If it works , Thank you for clicking three times !!!️