# -*- coding: utf-8 -*-
# @Time : 2023-03-18 15:03
# @Author : AmoXiang
# @File : 5.查询文档.py
# @Software: PyCharm
# @Blog : https://blog.csdn.net/xw1680
from bson.objectid import ObjectId
from pymongo import MongoClient, ASCENDING, DESCENDING
class LearnMongoDBSearch(object):
""" MongoDB查询练习 """
def __init__(self):
self.client = MongoClient()
def search_one(self):
""" 查询一个文档 """
temp_obj = self.client.test.newdb.find_one()
print(temp_obj)
print('喜欢分数:', temp_obj['likes'])
# print('注册时间:', temp_obj['reg_date'].date())
print('姓名:', temp_obj['uname'])
def search_user_by_pk(self, pk):
obj_id = ObjectId(pk)
# user_obj = self.client.test.newdb.find_one({'_id': obj_id})
# 面向对象的方法,有代码提示
db = self.client.get_database('test')
users = db.get_collection('newdb')
user_obj = users.find_one({'_id': obj_id})
print(user_obj)
def search_many(self):
""" 查询多个文档 """
db = self.client.get_database('test')
students = db.get_collection('students')
# stu_list = students.find()
# for item in stu_list:
# print(item)
# 查询年龄大于12岁的学生
stu_list = students.find({'age': {'$gt': 12}}, {'stu_name': 1, 'class_name': 1, 'age': 1})
for item in stu_list:
# 注意: mongo中存储的整数转换成了浮点数
print(item)
def paginate(self, page=1, page_size=10):
"""
分页处理
:param page: 当前的页
:param page_size: 每一页数据大小
:return:
"""
db = self.client.get_database('test')
students = db.get_collection('students')
offset = (page - 1) * page_size
stu_list = students.find().skip(offset).limit(page_size)
return stu_list
def sort_data(self):
""" 排序 """
db = self.client.get_database('test')
grades = db.get_collection('grades')
# // 将学生的语文成绩从高到低排序
# db.grades.find({"grade.course_name": "语文"}).sort({"grade.score": -1});
#
# //将学生的语文成绩按照年龄和成绩排序
# db.grades.find({"grade.course_name": "语文"}).sort({"age": -1, "grade.score": -1});
# db.grades.find({"grade.course_name": "语文"}).sort({"grade.score": -1, "age": -1});
# 按某一列排序
# data_list = grades.find({"grade.course_name": "语文"}).sort("grade.score", DESCENDING);
# for item in data_list:
# print(item)
# 按多列排序
data_list = grades.find({"grade.course_name": "语文"}).sort([('age', DESCENDING),("grade.score", DESCENDING),])
for item in data_list:
print(item)
def counter_students(self):
""" 统计newdb中文档总数 """
db = self.client.get_database('test')
newdb = db.get_collection('newdb')
# result = newdb.count_documents({})
result = newdb.count_documents({"uname": {"$eq": "张三"}})
print(result)
def test_aggregate(self):
"""
聚合统计:及格的学生成绩
"""
db = self.client.get_database('test')
grades = db.get_collection('grades')
result = grades.aggregate([
# //where
{
'$match': {"grade.score": {'$gte': 60}}
},
# //group by
{
'$group': {
'_id': "$stu_no",
'total': {'$sum': 1}
}
},
# // having
{
'$match': {
'total': {'$eq': 3}
}
}
])
for item in result:
print(item)
if __name__ == '__main__':
obj = LearnMongoDBSearch()
# obj.search_one()
# obj.search_user_by_pk('6411ee77b6170000b4003f95')
# obj.search_many()
# stu_list = obj.paginate(page=3)
# for item in stu_list:
# print(item)
# obj.sort_data()
# obj.counter_students()
obj.test_aggregate()
|