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)})
mongoDB简单查询
最新推荐文章于 2024-07-23 16:06:03 发布
本文介绍了如何使用Python的pymongo库连接MongoDB数据库,包括初始化连接、设置认证、执行基本查询、聚合操作以及使用$unwind进行数据扁平化。
摘要由CSDN通过智能技术生成