Python实践
# 安装
python -m pip install pymongo
# 连接
from pymongo import MongoClient
# 示例1
# uri = "mongodb://<db_username>:<db_password>@<hostname:<port>"
uri = "mongodb://root:123456@localhost:27017"
client = MongoClient(uri)
# 示例2:启用 TLS
client = pymongo.MongoClient("mongodb://<db_username>:<db_password>@<hostname:<port>", tls=True)
# 示例3:允许不安全的 TLS
client = pymongo.MongoClient("mongodb://<db_username>:<db_password>@<hostname:<port>",
tls=True,
tlsInsecure=True)
MongoClient
对象代表一个数据库连接池,因此大多数应用程序只需要一个MongoClient
实例
示例:
import os
from pymongo import MongoClient
try:
MONGODB_USERNAME = os.environ.get("MONGODB_USERNAME", "root")
MONGODB_PASSWORD = os.environ.get("MONGODB_PASSWORD", "123456")
MONGODB_HOST = os.environ.get("MONGODB_HOST", "localhost")
MONGODB_PORT = os.environ.get("MONGODB_PORT", "27017")
client = MongoClient(f"mongodb://{MONGODB_USERNAME}:{MONGODB_PASSWORD}@{MONGODB_HOST}:{MONGODB_PORT}/" )
client.admin.command("ping")
print("Connected successfully")
# other application code
client.close()
except Exception as e:
raise Exception(
"The following error occurred: ", e)
# 数据库操作
# 选择(创建)
# 指定数据库(无需提前建库,在首次插入数据时隐式创建)
database = client["test_database"]
# 集合操作
# 列表
collection_list = database.list_collections()
for c in collection_list:
print(c)
# 选择(创建)
# 指定集合,如不存在,会自动创建
database.get_collection("example_collection")
# 创建集合,【不建议使用】,重复创建会抛CollectionInvalid异常
database.create_collection("example_collection")
# 删除
collection = database["test_collection"];
collection.drop();
# 文档操作
# 插入 - 一个
result = collection.insert_one({ "<field name>" : "<value>" })
print(result.acknowledged)
# 插入 - 批量
document_list = [
{ "<field name>" : "<value>" },
{ "<field name>" : "<value>" }
]
result = collection.insert_many(document_list)
print(result.acknowledged)
# 更新 - 一个
query_filter = { "<field to match>" : "<value to match>" }
update_operation = { "$set" :
{ "<field name>" : "<value>" }
}
result = collection.update_one(query_filter, update_operation)
print(result.modified_count)
# 更新 - 批量
query_filter = { "<field to match>" : "<value to match>" }
update_operation = { "$set" :
{ "<field name>" : "<value>" }
}
result = collection.update_many(query_filter, update_operation)
print(result.modified_count)
# 覆盖 - 一个
query_filter = { "<field to match>" : "<value to match>" }
replace_document = { "<new document field name>" : "<new document value>" }
result = collection.replace_one(query_filter, replace_document)
print(result.modified_count)
# 删除 - 一个
query_filter = { "<field to match>" : "<value to match>" }
result = collection.delete_one(query_filter)
print(result.deleted_count)
# 删除 - 批量
query_filter = { "<field to match>" : "<value to match>" }
result = collection.delete_many(query_filter)
print(result.deleted_count)
# 参考
上次更新: 2024/10/27, 22:58:29