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

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

问题描述

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

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

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

解决方案

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.

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

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.

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.

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天全站免登陆