如何在 MongoDB 中按字段值排序 [英] How to ORDER BY FIELD VALUE in MongoDB
本文介绍了如何在 MongoDB 中按字段值排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Mysql中,我经常在ORDER BY
子句中使用FIELD()
函数:
In Mysql I often use the FIELD()
function in the ORDER BY
clause:
按字段排序(id, '1', '6', '3', ...);
如何在 MongoDB 中获得相同的结果?我尝试了以下方法:
How does one get the same results in MongoDB? I tried the following:
.find(...).sort({id: [1, 6, 3]})
这不起作用
推荐答案
所以记录一下:
给定数组 [1,6,3]
你想要的查询是这样的:
Given the array [1,6,3]
what you want in your query is this:
db.collection.aggregate([
{ "$project": {
"weight": { "$cond": [
{ "$eq": ["_id": 1] },
3,
{ "$cond": [
{ "$eq": ["_id": 6] },
2,
{ "$cond": [
{ "$eq": ["_id": 3] },
1,
0
]},
]},
]}
}},
{ "$sort": { "weight": -1 } }
])
这会按照输入的数组"顺序为您提供特定的权重",以投影"结果的权重.
And that gives you specific "weights" by order of your "array" of inputs to "project" weights upon the results.
这篇关于如何在 MongoDB 中按字段值排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文