按值对项目排序mongodb [英] Sort item by value mongodb

查看:80
本文介绍了按值对项目排序mongodb的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过将具有特定值的项目放在其他项目之前对集合进行排序.

I want to sort a collection by putting items with a specific values before other items.

例如,我希望所有带有"getthisfirst": "yes"的项目都在所有其他项目之前.

For example I want all the items with "getthisfirst": "yes" to be before all the others.

{"getthisfirst": "yes"}
{"getthisfirst": "yes"}
{"getthisfirst": "no"}
{"getthisfirst": "maybe"}

推荐答案

这是一个一般概念,称为加权".因此,如果没有其他任何机制,那么您可以通过将权重"的值逻辑投影"到文档中,从而在MongoDB查询中进行逻辑处理.

This as a general concept is called "weighting". So without any other mechanism in place, then you handle this logically in a MongoDB query by "projecting" the values for the "weight" into the document logically.

用于投影"和更改文档中存在的字段的方法是 $project 管道阶段:

Your method for "projecting" and altering the fields present in your document is the .aggregate() method, and specifically it's $project pipeline stage:

db.collection.aggregate([
    { "$project": {
        "getthisfirst": 1,
        "weight": {
            "$cond": [
                { "$eq": [ "$getthisfirst", "yes" ] },
                10,
                { "$cond": [
                    { "$eq": [ "$getthisfirst", "maybe" ] },
                    5,
                    0
                ]}
            ]
        }
    }},
    { "$sort": { "weight": -1 } }
]);

$cond 运算符是三元" (if/then/else)条件,其中第一个参数是条件语句到达布尔值true|false.如果true"then",则返回第二个参数作为结果,否则返回"else"或第三个参数作为响应.

The $cond operator here is a "ternary" ( if/then/else ) condition where the first argument is a conditional statment arriving to boolean true|false. If true "then" the second argument is returned as the result, otherwise the "else" or third argument is returned in response.

在这种嵌套"情况下,如果是"是匹配项,则分配某个权重"分数,否则,我们继续进行下一个条件测试,其中当可能"是匹配项时,注释者分数为分配,否则得分为0,因为我们只有三个匹配的可能性.

In this "nested" case, then where the "yes" is a match then a certain "weight" score is assigned, otherwise we move on to the next condition test where when "maybe" is a match then anoter score is assigned, or otherwise the score is 0 since we only have three posibilities to match.

然后 $sort 应用条件是为了对结果进行排序"(以降序排列),并以最大"权重放在顶部.

Then the $sort condition is applied in order to, well "order" ( in decending order ) the results with the largest "weight" on top.

这篇关于按值对项目排序mongodb的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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