不同类别的MongoDB查询
创始人
2025-01-09 07:00:16
0次

以下是一些不同类别的MongoDB查询的解决方法,每个类别都包含了代码示例。

  1. 插入文档:
from pymongo import MongoClient

# 创建MongoDB客户端
client = MongoClient()

# 连接到数据库
db = client.test

# 连接到集合(表)
collection = db.my_collection

# 插入单个文档
document = {"name": "John", "age": 25}
result = collection.insert_one(document)
print(result.inserted_id)

# 插入多个文档
documents = [
    {"name": "Alice", "age": 30},
    {"name": "Bob", "age": 35}
]
result = collection.insert_many(documents)
print(result.inserted_ids)
  1. 查询文档:
from pymongo import MongoClient

# 创建MongoDB客户端
client = MongoClient()

# 连接到数据库
db = client.test

# 连接到集合(表)
collection = db.my_collection

# 查询单个文档
document = collection.find_one({"name": "John"})
print(document)

# 查询多个文档
documents = collection.find({"age": {"$gt": 30}})
for doc in documents:
    print(doc)
  1. 更新文档:
from pymongo import MongoClient

# 创建MongoDB客户端
client = MongoClient()

# 连接到数据库
db = client.test

# 连接到集合(表)
collection = db.my_collection

# 更新单个文档
result = collection.update_one(
    {"name": "John"},
    {"$set": {"age": 26}}
)
print(result.modified_count)

# 更新多个文档
result = collection.update_many(
    {"age": {"$gt": 30}},
    {"$inc": {"age": 1}}
)
print(result.modified_count)
  1. 删除文档:
from pymongo import MongoClient

# 创建MongoDB客户端
client = MongoClient()

# 连接到数据库
db = client.test

# 连接到集合(表)
collection = db.my_collection

# 删除单个文档
result = collection.delete_one({"name": "John"})
print(result.deleted_count)

# 删除多个文档
result = collection.delete_many({"age": {"$gt": 30}})
print(result.deleted_count)

这些示例代码提供了插入、查询、更新和删除MongoDB文档的基本操作方法。根据具体需求可以进行相应的调整和扩展。

相关内容

热门资讯

2027版作弊器!斗棋恩施麻将... 2027版作弊器!斗棋恩施麻将作弊器多功能AI教程,斗棋恩施麻将果然是有作弊器教程一、斗棋恩施麻将游...
2027版外挂!芷芷休闲外挂多... 2027版外挂!芷芷休闲外挂多功能AIapp,芷芷休闲其实有外挂app一、芷芷休闲游戏安装教程牌型概...
2027版辅助器!和悦游戏辅助... 2027版辅助器!和悦游戏辅助器多功能AI攻略,和悦游戏本来真的有辅助器攻略一、和悦游戏可以开透视的...
2027版外挂!相约麻将外挂多... 2027版外挂!相约麻将外挂多功能AI教程,相约麻将确实是真的有外挂教程1、相约麻将公共底牌简单,相...
2027版透视器!中至赣州透视... 2027版透视器!中至赣州透视器多功能AIapp,中至赣州本来真的是有透视器app中至赣州脚本下载中...
2027版透视器!乐安闲趣麻将... 2027版透视器!乐安闲趣麻将透视器多功能AI工具,乐安闲趣麻将本来存在有透视器工具一、乐安闲趣麻将...
2027版透视挂!来局麻将透视... 2027版透视挂!来局麻将透视挂多功能AI教程,来局麻将真是有透视挂教程进入游戏-大厅左侧-新手福利...
2027版外挂!优优龙岩麻将外... 2027版外挂!优优龙岩麻将外挂多功能AIapp,优优龙岩麻将切实有外挂app1、优优龙岩麻将免费辅...
2027版透视挂!牛郎棋牌透视... 2027版透视挂!牛郎棋牌透视挂多功能AI教程,牛郎棋牌其实有透视挂教程牛郎棋牌破解侠是真的助透视。...
2027版外挂!麻将胡了2外挂... 2027版外挂!麻将胡了2外挂多功能AI插件,麻将胡了2竟然存在有外挂插件所有人都在同一条线上,像星...