根据mongdb聚合中的字符串值提供排序顺序 [英] Provide a sort order from string values in mongdb aggregation

查看:101
本文介绍了根据mongdb聚合中的字符串值提供排序顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个包含如下文档的集合:

Let's say I have a collection with documents that look like this:

{
    _id: <someMongoId>,
    status: 'start'
    otherImportantData: 'Important!'
}

...并且状态可以是开始",中间"或结束".

...and status can be 'start', 'middle', or 'end'.

我想按状态字段对这些文档(特别是在聚合框架中)进行排序-但我不希望按字母顺序对其进行排序;我想按开始顺序->中间->结束顺序进行排序.

I want to sort these documents (specifically in the aggregation framework) by the status field - but I don't want it in alphabetical order; I want to sort in the order start -> middle -> end.

我一直在寻找某种方法来将status字段投影到一个数字型的statusValue字段中(以及我可以指定每个字符串映射到的数字的位置),尽管我很乐意看任何其他选择.

I've been looking for some way to project the status field to a statusValue field that is numeric (and where I get to dictate the numbers each string maps to), although I'd be happy to look at any alternatives.

假设我可以做到.我会选择status并将其映射为这样:

Let's say I could do that. I'd take status and map it as such:

start: 1
middle: 2
end: 3
<anything else>: 0

然后我可以在聚合管道中执行以下操作:

then I could do something like this in the aggregation pipeline:

{
    $sort: { statusValue : 1 }
}

...但是我不确定如何将这些状态映射到聚合管道中.

...but I'm not sure how to get those statuses mapped in the aggregation pipeline.

如果没有办法,至少我会停止寻找.下一个最佳方法是什么?使用MongoDB中的Map-Reduce功能?

If there is no way to do it, at least I'll know to stop looking. What would be the next best way? Using the Map-Reduce features in MongoDB?

推荐答案

您可以在3.4中尝试以下聚合.

You can try below aggregation in 3.4.

使用 $indexOfArray 来定位搜索位置值列表中的字符串,并 $addFields 以保留输出在文档的额外字段中进行索引,后跟 $sort 整理文件

Use $indexOfArray to locate the position of search string in list of values and $addFields to keep the output index in the extra field in the document followed by $sort to sort the documents

[
 {"$addFields":{ "statusValue":{"$indexOfArray":[[start, middle, end], "$status"]}}}, 
 {"$sort":{"statusValue":1}}
]

这篇关于根据mongdb聚合中的字符串值提供排序顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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