0.前言
最近,我在做算法标签系统,打算用MongoDB进行数据数据存储。首先,用pip install pymongo
进行MongoDB的安装包安装。
1.Python-MongoDB客户端
import pymongo
from bson import ObjectId
# 创建MongoDB的客户端
client = pymongo.MongoClient("192.168.110.180", 27017)
# 查看MongoDB所有的数据库名称
print(client.list_database_names())
# 切换MongoDB的数据库,当itoe数据库不存在时,创建该数据库
db = client["itoe"]
# 切换MongoDB的集合
collection = db['itoe']
# 测试样例json字符串,可以通过 "_id":""指定插入文档的ID,该配置缺省时,MongoDB会默认分配一个Object("")类型的ID
test = {
"sites": [
{"name": "菜鸟教程", "url": "www.runoob.com"},
{"name": "google", "url": "www.google.com"},
{"name": "微博", "url": "www.weibo.com"}
]
}
# 向MongoDB中插入一条文档
result = collection.insert_one(test)
# 返回结果查看是否插入成功
print(result.acknowledged)
# 返回插入成功后的ID
print(result.inserted_id)
# 可以根据ID进行查询返回一条文档,可以通过其他条件返回多条文档
x = collection.find({'name': '菜鸟教程'})
# 遍历结果数据集返回查询结果
for i in x:
print(i)
# 根据指定ID进行查找,_id等于1的
x = collection.find_one({'_id': '1'})
# 输出查询的结果
print(x)
# 根据系统分配的ID进行数据查询
y = collection.find_one({'_id': ObjectId('636231807191970fb7963bfd')})
# 输出查询结果
print(y)
# 查询所有文档
findAll = collection.find({})
# 输出所有文档
for i in findAll:
print(i)
# t = pymongo.MongoClient("192.168.110.180", 27017)['itoe']['itoe'].find({})
# for i in t:
# print(i)
# 根据指定ID删除文档
x1 = collection.delete_one({"_id": "1"})
# 返回数据是
print(x1.acknowledged)
# 返回删除文档的条数
print(x1.deleted_count)
# 返回删除数据的结果
print(x1.raw_result)
# 删除所有文档
result1 = collection.delete_many({})
# 返回是否删除成功
print(result1.acknowledged)
# 返回删除的数量
print(result1.deleted_count)
# 返回删除的结果行
print(result1.raw_result)