下载python库
pip install pymongo
连接数据库
from pymongo import MongoClient
conn = MongoClient("localhost", 27017) # IP,端口号
db = conn.mydb # 数据库的名称
collection = db.student # 获取集合
conn.close() # 断开连接
添加操作
collection.insert({"name": "s-tjl", "age": 19, "gender": 1, "addr": "河南", "idDelete": 0}) # 单条数据添加
collection.insert([
{"name": "h-tjl", "age": 19, "gender": 1, "addr": "河南", "idDelete": 0},
{"name": "x-tjl", "age": 21, "gender": 0, "addr": "河南", "idDelete": 0}
]) # 多条数据添加
更新操作
collection.update({"name": "h-tjl"}, {"$set": {"age": 25}})
查询操作
--------- 普通查询 ------------
res = collection.find({"age": {"$gt": 18}})
for i in res:
# 字典类型
print(type(i))
--------- 统计查询 -----------
res = collection.find({"age": {"$gt": 18}}).count()
--------- 根据ID查询 -----------
res = collection.find({"_id": ObjectId("5c8e1f3d39d5143ab851b202")}) #返回一个列表
---------- sort排序 ---------------
# 升序
res = collection.find().sort("age")
for i in res:
print(i)
# 降序
res = collection.find().sort("age", pymongo.DESCENDING)
for i in res:
print(i)
删除操作
collection.remove({'name': "h-tjl"}) # 删除文档