【mongo数据库与python交互】
程序员文章站
2022-05-19 11:58:01
...
目录
一、添加文档
1、添加单个文档
from pymongo import MongoClient
# 连接服务器
conn = MongoClient('localhost',27017)
# 连接数据库
db = conn.mydb
# 获取集合
collection = db.student
# 添加文档
collection.insert_one({'name':"天下第一帅",'age':18,'gender':1,'address':'北京','isDelete':0})
# 断开
conn.close()
2、添加多个文档
from pymongo import MongoClient
# 连接服务器
conn = MongoClient('localhost', 27017)
# 连接数据库
db = conn.mydb
# 获取集合
collection = db.student
# 添加文档
collection.insert_many([{'name': "天下第一帅", 'age': 18, 'gender': 1, 'address': '北京', 'isDelete': 0},
{'name': "第一帅", 'age': 33, 'gender': 1, 'address': '珠江', 'isDelete': 0}]
)
# 断开
conn.close()
二、查询文档
1、根据条件查询文档
from pymongo import MongoClient
# 连接服务器
conn = MongoClient('localhost', 27017)
# 连接数据库
db = conn.mydb
# 获取集合
collection = db.student
# 查询文档
# 查询部分文档
res = collection.find({'age': {'$gt': 30}})
for row in res:
print(row)
print(type(row))
# 断开
conn.close()
2、查询全部文档
from pymongo import MongoClient
# 连接服务器
conn = MongoClient('localhost', 27017)
# 连接数据库
db = conn.mydb
# 获取集合
collection = db.student
# 查询全部文档
res = collection.find()
for row in res:
print(row)
print(type(row))
# 断开
conn.close()
3、根据ID查询
from pymongo import MongoClient
from bson.objectid import ObjectId
# 连接服务器
conn = MongoClient('localhost', 27017)
# 连接数据库
db = conn.mydb
# 获取集合
collection = db.student
res = collection.find({'_id':ObjectId('5e95cdac5558adb496644f21')})
for row in res:
print(row)
# 断开
conn.close()
4、查出来的结果进行排序
from pymongo import MongoClient
from bson.objectid import ObjectId
import pymongo
# 连接服务器
conn = MongoClient('localhost', 27017)
# 连接数据库
db = conn.mydb
# 获取集合
collection = db.student
'''
排序
升序
res = collection.find().sort('age')
for row in res:
print(row)
降序
res = collection.find().sort('age',pymongo.DESCENDING)
for row in res:
print(row)
分页 越过3条拿3条
res = collection.find().skip(3).limit(3)
for row in res:
print(row)
'''
# 断开
conn.close()
三、更新文档
from pymongo import MongoClient
from bson.objectid import ObjectId
# 连接服务器
conn = MongoClient('localhost', 27017)
# 连接数据库
db = conn.mydb
# 获取集合
collection = db.student
collection.update_one({"name":"wanglei"},{'$set':{'age':15}})
# 断开
conn.close()
四、删除文档
from pymongo import MongoClient
from bson.objectid import ObjectId
# 连接服务器
conn = MongoClient('localhost', 27017)
# 连接数据库
db = conn.mydb
# 获取集合
collection = db.student
collection.delete_one({"name":"wanglei"})
# 断开
conn.close()
上一篇: R语言计算相关性和p-values
下一篇: R语言20-变量相关性