MongoDB聚合統計數組內的某個字段的個數並排序


開門見山的說

最近使用mongodb來作為后端數據庫,flask來做api服務器,Mongoengine來做ORM,結果遇到挺多的麻煩,歸根結底是自己對於mongodb的不夠了解導致的,故做個筆記

  • 數據類型樣式
{
    "_id" : ObjectId("5e5a32fe2a89d7c2fc05b9fc"),
    "user" : "1",
    "score" : 100,
    "class" : "A",
}
{
    "_id" : ObjectId("5e5a33092a89d7c2fc05ba07"),
    "user" : "2",
    "score" : 100,
    "class" : "A",
}
{
    "_id" : ObjectId("5e5a33092a89d7c2fc05ba07"),
    "user" : "3",
    "score" : 90,
    "class" : "B",
}
  • $match:過濾數據,返回符合條件的數據
def aggregate():
    # 構造過濾條件
    match_dic = {"$match": {'class': {'$ne': ''}}}
    # 通過Mongoengine的模型獲取到文檔對象
    result = Model._get_collection().aggregate([match_dic])
    for one in result:
        print(one)
  • $group:將過濾后的數據進行分組
def aggregate_match_group(self):
    match_dic = {"$match": {'class': {'$ne': ''}}}
    # 以分數score來分組,並且統計該分數下共有多少個數
    group_dic = {"$group": {
            '_id': "$score",
            'num': {'$sum': 1}
        }}
    result = Model._get_collection().aggregate([match_dic, group_dic])
    for one in result:
        print(one)
  • 分組后獲取某個字段的總和
def aggregate_match_group(self):
    match_dic = {"$match": {'class': {'$ne': ''}}}
    # 以分數score來分組,並且統計該分數下的總和
    group_dic = {"$group": {
            '_id': "$score",
            'num': {'$sum': '$score'}
        }}
    result = Model._get_collection().aggregate([match_dic, group_dic])
    for one in result:
        print(one)
  • 多條件分組,並統計數量
def aggregate_match_group(self):
    # 為空表示所有都進行分組 
    match_dict = {"$match": {}}
    # 以分數score來分組,並且統計該分數下的總和
    group_dic = {"$group":{"_id":{"年齡":"$age","性別":"$gender"},"人數":{"$sum":1}}}
    result = Model._get_collection().aggregate([match_dic, group_dic])
    for one in result:
        print(one)

{'_id': {'年齡': '100', '性別': '女'}, '人數': 2}
{'_id': {'年齡': '100', '性別': '男'}, '人數': 2}
  • 對結果進行排序
def aggregate_match_group(self):
    match_dic = {"$match": {'class': {'$ne': ''}}}
    # 以分數score來分組,並且統計該分數下的總和
    group_dic = {"$group": {
            '_id': "$score",
            'num': {'$sum': '$score'}
        }}
    sort_dic = {
        "$sort": {
            'num': -1
        }
    }

    result = Model._get_collection().aggregate([match_dic, group_dic, sort_dic])
    for one in result:
        print(one)

管道操作符

常用管道    含義
$group    將collection中的document分組,可用於統計結果
$match    過濾數據,只輸出符合結果的文檔
$project    修改輸入文檔的結構(例如重命名,增加、刪除字段,創建結算結果等)
$sort    將結果進行排序后輸出
$limit    限制管道輸出的結果個數
$skip    跳過制定數量的結果,並且返回剩下的結果
$unwind    將數組類型的字段進行拆分

表達式操作符

常用表達式    含義
$sum    計算總和,{$sum: 1}表示返回總和×1的值(即總和的數量),使用{$sum: '$制定字段'}也能直接獲取制定字段的值的總和
$avg    平均值
$min    min
$max    max
$push    將結果文檔中插入值到一個數組中
$first    根據文檔的排序獲取第一個文檔數據
$last    同理,獲取最后一個數據


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM