如何在MongoDB中按字段值排序

编程入门 行业动态 更新时间:2024-10-23 13:25:56
本文介绍了如何在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中按字段值排序

本文发布于:2023-11-22 13:54:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1617699.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字段   如何在   MongoDB

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!