如何在 MongoDB 中执行基于值的 Order By? [英] How to perform a value based Order By in MongoDB?

查看:38
本文介绍了如何在 MongoDB 中执行基于值的 Order By?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

select * from users ORDER BY FIELD(status, 'A', 'B', 'C', 'D') ASC; 

这将根据他们的状态对所有用户进行排序,这样所有状态为A"的用户将首先出现,然后是B",依此类推.MongoDB 中的等价物是什么?

This will sort all the users according to their statuses such that all the users with status 'A' will come first then 'B' and so on. What would be an equivalent in MongoDB?

推荐答案

您需要$project MongoDB 术语中每个值的权重",这意味着 .aggregate() 方法:

You need to $project a "weight" for each value in order in MongoDB terms, and that means the .aggregate() method:

db.users.aggregate([
    { "$project": {
        "status": 1,
        "a_field": 1,
        "another_field": 1,
        "pretty_much_every_field": 1,
        "weight": {
            "$cond": [
                { "$eq": [ "$status", "A" ] },
                10,
                { "$cond": [ 
                    { "$eq": [ "$status", "B" ] },
                    8,
                    { "$cond": [
                        { "$eq": [ "$status", "C" ] },
                        6,
                        { "$cond": [
                            { "$eq": [ "$status", "D" ] },
                            4,
                            0
                        ]}
                    ]}
                ]}
            ] 
        }
    }},
    { "$sort": { "weight": -1 } }
])

三元的嵌套使用 $cond 允许将状态"的每个项目视为有序的权重"值按照给定参数的顺序.

The nested use of the ternary $cond allows each item for "status" to be considered as an ordered "weight" value in the order of the arguments given.

这反过来又被提供给 $sort,其中投影值(权重")用于根据加权匹配对结果进行排序.

This in turn is fed to $sort, where the projected value ( "weight" ) is used to sort the results as scored by the weighted matching.

因此,通过这种方式,优先考虑状态"匹配的顺序,即哪个首先出现在排序结果中.

So in this way the preference is given to the order of "status" matches as to which appears first in the sorted results.

这篇关于如何在 MongoDB 中执行基于值的 Order By?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆