如何在MongoDB中按字段值排序 [英] How to ORDER BY FIELD VALUE in MongoDB

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

问题描述

在Mysql中,我经常在ORDER BY子句中使用FIELD()函数:

In Mysql I often use the FIELD() function in the ORDER BY clause:

ORDER BY FIElD(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屋!

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