NipGeihou's blog NipGeihou's blog
  • Java

    • 开发规范
    • 进阶笔记
    • 微服务
    • 快速开始
    • 设计模式
  • 其他

    • Golang
    • Python
    • Drat
  • Redis
  • MongoDB
  • 数据结构与算法
  • 计算机网络
  • 应用

    • Grafana
    • Prometheus
  • 容器与编排

    • KubeSphere
    • Kubernetes
    • Docker Compose
    • Docker
  • 组网

    • TailScale
    • WireGuard
  • 密码生成器
  • 英文单词生成器
🍳烹饪
🧑‍💻关于
  • 分类
  • 标签
  • 归档

NipGeihou

我见青山多妩媚,料青山见我应如是
  • Java

    • 开发规范
    • 进阶笔记
    • 微服务
    • 快速开始
    • 设计模式
  • 其他

    • Golang
    • Python
    • Drat
  • Redis
  • MongoDB
  • 数据结构与算法
  • 计算机网络
  • 应用

    • Grafana
    • Prometheus
  • 容器与编排

    • KubeSphere
    • Kubernetes
    • Docker Compose
    • Docker
  • 组网

    • TailScale
    • WireGuard
  • 密码生成器
  • 英文单词生成器
🍳烹饪
🧑‍💻关于
  • 分类
  • 标签
  • 归档
  • MySQL

  • Redis

  • MongoDB

    • 教程

      • 概念与准备
      • 常见操作
      • Python实践
        • 安装
        • 连接
        • 数据库操作
          • 选择(创建)
        • 集合操作
          • 列表
          • 选择(创建)
          • 删除
        • 文档操作
          • 插入 - 一个
          • 插入 - 批量
          • 更新 - 一个
          • 更新 - 批量
          • 覆盖 - 一个
          • 删除 - 一个
          • 删除 - 批量
        • 参考
  • 分享

  • 数据库
  • MongoDB
  • 教程
NipGeihou
2024-10-27
目录

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)

# 参考

  • MongoDB PyMongo 文档 — PyMongo v 4.10 (opens new window)
上次更新: 2024/10/27, 22:58:29
常见操作
数据库的选择

← 常见操作 数据库的选择→

最近更新
01
Docker Swarm
04-18
02
安全隧道 - gost
04-17
03
Solana最佳实践
04-16
更多文章>
Theme by Vdoing | Copyright © 2018-2025 NipGeihou | 友情链接
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式