按值排序项目 mongodb
Sort item by value mongodb
我想通过将具有特定值的项目放在其他项目之前来对集合进行排序。
例如,我希望带有 "getthisfirst": "yes"
的所有项目都排在所有其他项目之前。
{"getthisfirst": "yes"}
{"getthisfirst": "yes"}
{"getthisfirst": "no"}
{"getthisfirst": "maybe"}
这个作为一般概念叫做"weighting"。因此,如果没有任何其他机制,那么您可以在 MongoDB 查询中通过 "projecting" 将 "weight" 的值逻辑地处理到文档中。
您 "projecting" 和更改文档中存在的字段的方法是 .aggregate()
method, and specifically it's $project
管道阶段:
db.collection.aggregate([
{ "$project": {
"getthisfirst": 1,
"weight": {
"$cond": [
{ "$eq": [ "$getthisfirst", "yes" ] },
10,
{ "$cond": [
{ "$eq": [ "$getthisfirst", "maybe" ] },
5,
0
]}
]
}
}},
{ "$sort": { "weight": -1 } }
]);
$cond
operator here is a "ternary" ( if/then/else ) 条件,其中第一个参数是到达布尔值 true|false
的条件语句。如果 true
"then" 第二个参数作为结果返回,否则返回 "else" 或第三个参数作为响应。
在这种 "nested" 情况下,如果 "yes" 匹配,则分配特定的 "weight" 分数,否则我们继续下一个条件测试,其中 "maybe" 是一个匹配,然后分配另一个分数,否则分数是 0
因为我们只有三个匹配的可能性。
然后应用 $sort
条件,以便 "order"(按降序排列)最大的 "weight" 在顶部的结果。
我想通过将具有特定值的项目放在其他项目之前来对集合进行排序。
例如,我希望带有 "getthisfirst": "yes"
的所有项目都排在所有其他项目之前。
{"getthisfirst": "yes"}
{"getthisfirst": "yes"}
{"getthisfirst": "no"}
{"getthisfirst": "maybe"}
这个作为一般概念叫做"weighting"。因此,如果没有任何其他机制,那么您可以在 MongoDB 查询中通过 "projecting" 将 "weight" 的值逻辑地处理到文档中。
您 "projecting" 和更改文档中存在的字段的方法是 .aggregate()
method, and specifically it's $project
管道阶段:
db.collection.aggregate([
{ "$project": {
"getthisfirst": 1,
"weight": {
"$cond": [
{ "$eq": [ "$getthisfirst", "yes" ] },
10,
{ "$cond": [
{ "$eq": [ "$getthisfirst", "maybe" ] },
5,
0
]}
]
}
}},
{ "$sort": { "weight": -1 } }
]);
$cond
operator here is a "ternary" ( if/then/else ) 条件,其中第一个参数是到达布尔值 true|false
的条件语句。如果 true
"then" 第二个参数作为结果返回,否则返回 "else" 或第三个参数作为响应。
在这种 "nested" 情况下,如果 "yes" 匹配,则分配特定的 "weight" 分数,否则我们继续下一个条件测试,其中 "maybe" 是一个匹配,然后分配另一个分数,否则分数是 0
因为我们只有三个匹配的可能性。
然后应用 $sort
条件,以便 "order"(按降序排列)最大的 "weight" 在顶部的结果。