MongoDB与python 交互

时间:2023-12-27 23:31:31

一、安装pymongo

MongoDB与python 交互

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

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

二、MongoDB与python 交互

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

MongoDB与python 交互

# 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