mongoDB简单查询

本文介绍了如何使用Python的pymongo库连接MongoDB数据库,包括初始化连接、设置认证、执行基本查询、聚合操作以及使用$unwind进行数据扁平化。
摘要由CSDN通过智能技术生成
from  pymongo import MongoClient

class MongoTest:
	config = {"user": "username", "password": "xxxxxxx", "nodes": "x.x.x.x:8635,x.x.x.x:8635", "db": "dbname"}
	def __init__(self):
		self.uri = "mongodb://{}/".format(self.config["nodes"])
		self.client = MongoClient(self.uri)
		self.client.admin.authenticate(self.config["user"],self.config["password"],mechanism='SCRAM-SHA-1')  #添加mongo连接认证方式
		self.db = self.client[self.config["db"]]
		
	def mongoQuery(self,collectionName,queryData):
		"""
		
		:param collectionName: collection名称
		:param queryData: 查询的匹配字段
		:return:
		"""
		collectionNames = self.db.list_collection_names() #获取当前db下的collection名称
		print("collection名称",collectionNames)
		print("collection信息:",self.db[collectionNames[1]])
		res = self.db[collectionNames[1]].find_one({})
		print(res)
		res = self.db[collectionName].find(queryData)
		# print(self.db[indexData])  #已字典形式访问该db下的数据文件,类似ES索引形式
		res = self.db[collectionNames[1]].find({"uuId":"1aba0c5affda4b52b173fc9446ff5099"})
		# mongo聚合操作 aggregate , $group 类似sql的group by 可以按多个条件进行查询
		res = self.db["collectionName"].aggregate([{"$group":{"_id":{"city":"$city","typeName":"$typeName"},"count":{"$sum":1}}}])
		#条件结果下进行分组查询,使用$match 进行匹配条件后进行分组
		res = self.db["collectionName"].aggregate([{"$match":{"city":510100}},{"$group":{"_id":{"city":"$city","typeName":"$typeName"},"count":{"$sum":1}}}])
		#匹配多个条件的查询的时候使用 $in 多个条件匹配
		res = self.db["collectionName"].aggregate([{"$match":{"city":{"$in":[510100,442000]}}},{"$group":{"_id":{"city":"$city","typeName":"$typeName"},"count":{"$sum":1}}}])
		#aggregate 聚合后的操作排序使用 $sort 进行排序,加上排序的条件 1 正序,-1 逆序,如下聚合后的按分组的count计数正序排序
		res = self.db["collectionName"].aggregate([{"$match":{"city":{"$in":[510100,442000]}}},{"$group":{"_id":{"city":"$city","typeName":"$typeName"},"count":{"$sum":1}}},{"$sort":{"count":1}}])
		
		# $unwind 字段操作的时候,先将数据扁平化,再根据条件进行匹配聚合数据
		res = self.db["collectionName"].aggregate([{"$unwind":"$cities"},{"$match":{"uuId":"5fbc4427b8cc4c64b2e36f4e18594913"}},{"$match":{"cities.city":440400}}])
		res = self.db["collectionName"].aggregate([{"$match": {"uuId": "5fbc4427b8cc4c64b2e36f4e18594913"}},{"$unwind": "$cities"},{"$match": {"cities.city": 440400}}])
		res = self.db["collectionName"].find({"projectId":"714012034454257735","planId":4991,"upperDate":datetime.datetime(2023,5,24,16,0)})

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值