MongoDB与python 交互

一、安装pymongo

注意 :当同时安装了python2和python3,为区分两者的pip,分别取名为pip2和pip3。

推荐:https://www.cnblogs.com/thunderLL/p/6643022.html

二、MongoDB与python 交互

2.1、打开黑屏终端,启动mongodb服务,运行mongo

# encoding=utf8
from pymongo import MongoClient
from bson.objectid import ObjectId
import pymongo

# 连接服务器
conn = MongoClient("localhost", 27017)

# 连接数据库
db = conn.text

# 获得集合
collection = db.sub

# 添加数据
collection.insert(
    {'name': 'dd', 'gender': 1, 'math': 30, 'chinese': 50}
)
# 查询文档
# res = collection.find()
# 查询部分文档
'''
res = collection.find({"math": {"$gt": 60}})
for row in res:
    print(row)
    print(type(row))
'''
# 统计查询
'''
res = collection.find({"math": {"$gt": 60}}).count()
print(res)
'''
# 根据id 查询
'''
res = collection.find({"_id":ObjectId('5b927e096e92f1c1d53e548f')})
print(res[0])
'''
# 排序
'''
res = collection.find().sort("math")  # 升序
res = collection.find().sort("math", pymongo.DESCENDING)
for row in res:
    print(row)
'''
# 分页查询
'''
res = collection.find().skip(3).limit(4)
for row in res:
    print(row)
'''

# 更新文档
'''
collection.update({"name": "bbb"}, {"$set": {"math": 100}})
'''
#删除
'''
collection.remove({"name": "dd"})
'''

# 断开
conn.close()
mongodb.py

 

转载于:https://www.cnblogs.com/Mint-diary/p/9608397.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值