MongoDB 自定义排序 - sevck
2021-11-03 12:48:00 Author: www.cnblogs.com(查看原文) 阅读量:53 收藏

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
        }
    }
]

)

【版权所有@Sevck 博客地址http://www.cnblogs.com/sevck】 可以转载,注明出处.


文章来源: http://www.cnblogs.com/sevck/p/15502945.html
如有侵权请联系:admin#unsafe.sh