MongoDB 自定义排序

Mongodb的排序函数sort()排序方式为:数字、中文首字母的顺序 升序(a-z)或者降序(z-a) 进行升序或者降序

db.getCollection('vuln').find({},{"_id":0,"severity":1,"vulnerability_id":1}).sort({"vulnerability_id":1})

 

 但是部分类别为单词,例如,low,medium,high 根据这个排序,简单的办法,录入的时候使用int来标记对应类别,但是如果整改比较麻烦,或者其他接口已经使用,也可以使用聚合查询

db.vuln.aggregate(

[
    {
        "$match": {
            "$and": [
                {
                    "domain": "test.a.com"
                }
            ],
            "is_delete": false
        }
    },
    {
        "$project": {
            "category": 1,
            "severity": {
                "$switch": {
                    "default": 0,
                    "branches": [
                        {
                            "case": {
                                "$eq": [
                                    "$severity",
                                    "low"
                                ]
                            },
                            "then": 1
                        },
                        {
                            "case": {
                                "$eq": [
                                    "$severity",
                                    "medium"
                                ]
                            },
                            "then": 2
                        },
                        {
                            "case": {
                                "$eq": [
                                    "$severity",
                                    "high"
                                ]
                            },
                            "then": 3
                        },
                        {
                            "case": {
                                "$eq": [
                                    "$severity",
                                    "critical"
                                ]
                            },
                            "then": 4
                        }
                    ]
                }
            },
            "is_delete": 1,
            "fix_status": 1,
            "title": 1,
            "definiteness": 1,
            "hash_id": 1
        }
    },
    {
        "$limit": 10
    },
    {
        "$skip": 0
    },
    {
        "$sort": {
            "severity": -1
        }
    }
]

)

 

posted @ 2021-11-03 11:48  sevck  阅读(1929)  评论(0编辑  收藏  举报