mongodb + python 使用with管理连接

本文介绍了一个使用Python的pymongo库连接MongoDB数据库并进行基本操作的例子,包括插入文档、查找文档及删除集合等操作。
import pymongo

class MongoConnection:
	def __init__(self, collection):
		self.db_url = 'mongodb://localhost:27017'
		self.db_name = 'store'
		self.col_name = collection
		self.user_name = 'pyclient'
		self.user_pwd = 'password'
		self.client = pymongo.MongoClient(
			self.db_url,
			socketTimeoutMS=5000
			)
		self.db = self.client[self.db_name]
		self.db.authenticate(self.user_name, self.user_pwd)
		self.collection = self.db[self.col_name]

	def __enter__(self):
		return  self.collection

	def __exit__(self, exc_type, exc_val, exc_tb):
		self.client.close()


if __name__ == '__main__':

	with MongoConnection('test') as conn:
		file_dict = {
		    "filename":"wahaha",
		    "filesize":100,
		    "DateTime":"2021-11-19 00:00:00"
			}

		res = conn.insert(file_dict)
		print(res)

		q = {'filename':'wahaha'}
		res = conn.find(q)
		print(list(res))

		res = conn.drop()
		print(res)
       

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

颹蕭蕭

白嫖?

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值