这个文章针对不懂mongodb的小伙伴进行简单指导
下面是python来操作mangodb
# author: liangzilong
from pymongo import MongoClient
# 连接到MongoDB服务器
client = MongoClient('mongodb://localhost:27017/')
# 选择数据库 一个数据库可以有多个集合
db = client['test_database']
# 选择集合
collection = db['test_collection']
def insert_data():
# 插入单个文档
document = {"name": "Alice", "age": 25, "city": "New York"}
collection.insert_one(document)
# 插入多个文档
documents = [
{"name": "Bob", "age": 30, "city": "San Francisco"},
{"name": "Charlie", "age": 35, "city": "Boston"},
{"name": "xx", "age": 35, "city": "Boston", "mix": {"name": "zs", 'age': "11"}}
]
collection.insert_many(documents)
def search_data():
# 查询单个文档
result = collection.find_one({"name": "Alice"})
print(result)
# 查询多个文档
results = collection.find({"city": "San Francisco"})
# 查询所有文档
results = collection.find({})
for doc in results:
print(doc)
def filter_data():
"""
gt gte lt lte and according specific field find
:return:
"""
documents = collection.find({"age": {"$gt": 25}})
for doc in documents:
print(doc)
def update_data():
"""
更新单个文档使用update_one方法,更新多个文档使用update_many方法。
:return:
"""
# 更新文档
collection.update_one({"name": "Alice"}, {"$set": {"age": 26}})
# 更新多个文档
collection.update_many({"city": "San Francisco"}, {"$set": {"age": 31}})
def delete_data():
# 删除单个文档
collection.delete_one({"name": "Alice"})
# 删除多个文档
collection.delete_many({"city": "San Francisco"})
def del_collection():
"""
delete one collection
:return:
"""
db.drop_collection('test_collection')
def delete_collection_data():
"""
delete collection all data
:return:
"""
result = collection.delete_many({})
# 输出删除的文档数量
print(f"Deleted {result.deleted_count} documents.")
def find_by_id():
from bson import ObjectId
# 查找单个文档 存在返回json 不存在返回None
document = collection.find_one({"_id": ObjectId("665eb56104189b983e534668")})
print(document)
上面只是一些简单的增删改查,下面我们进行系统的讲解: 主从备份、分片(replication)、and so on