Python操作MongoDB

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)
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

绝域时空

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值