使用Python进行MongoDB的数据插入查询

2023-04-15 00:00:00 查询 数据 插入

安装MongoDB驱动包pymongo:

pip install pymongo

连接MongoDB:

import pymongo

# 连接MongoDB服务器
client = pymongo.MongoClient("mongodb://localhost:27017/")

# 创建数据库
db = client["test"]

# 创建集合
collection = db["users"]

插入数据:

data = {"name": "张三", "age": 20, "company": "pidancode.com"}
# 插入一条数据
collection.insert_one(data)

datas = [{"name": "李四", "age": 22, "company": "皮蛋编程"}, 
         {"name": "王五", "age": 25, "company": "pidancode.com"}]
# 插入多条数据
collection.insert_many(datas)

查询数据:

# 查询一条数据
result = collection.find_one({"name": "张三"})
print(result)

# 查询所有数据
results = collection.find()
for result in results:
    print(result)

# 条件查询
results = collection.find({"company": "pidancode.com"})
for result in results:
    print(result)

更多操作请参见MongoDB官方文档:https://docs.mongodb.com/drivers/python/

相关文章