使用python操作Mongodb数据库

下载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"})  # 删除文档
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值