按值对项目进行排序 mongodb [英] Sort item by value 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.
投影"和更改文档中存在的字段的方法是 .aggregate()
方法,特别是 $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
运算符这里是一个 "ternary" ( if/then/else ) 条件其中第一个参数是到达布尔值 true|false
的条件语句.如果 true
则"第二个参数作为结果返回,否则返回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
<应用/strong> 条件是为了排序"(降序)具有最大权重"的结果在顶部.
Then the $sort
condition is applied in order to, well "order" ( in decending order ) the results with the largest "weight" on top.
这篇关于按值对项目进行排序 mongodb的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!