如何在mongo中按任意列表对对象数组进行排序 [英] how to sort array of objects by arbitrary list in mongo
问题描述
我一直在寻找一种通过任意列表对对象数组进行排序的方法.假设我有这个对象数组.
I was looking for a way to sort array of object by an arbitrary list. Lets assume I have this array of objects.
[
{
"_id": "4JEEuhNIae",
"category": "grocery"
},
{
"_id": "4JW7miNITl",
"category": "food"
},
{
"_id": "4Je4kmrrbZ",
"category": "coffee"
},
{
"_id": "4JgAh3N86x",
"category": "coffee"
}
]
这是我想用作排序条件的数组.带有food
的记录应该首先出现,然后是coffee
和grocery
.
This is the array that I would like to use as sorting criteria. Records with food
should come first, then coffee
and grocery
.
['food','coffee','grocery']
结果应为:
[
{
"_id": "4JW7miNITl",
"category": "food"
},
{
"_id": "4Je4kmrrbZ",
"category": "coffee"
},
{
"_id": "4JgAh3N86x",
"category": "coffee"
},
{
"_id": "4JEEuhNIae",
"category": "grocery"
},
]
如何使用mongoose在mongodb上进行这种类型的排序?我真的不想在获取数据后对代码进行任何操作.
How can I do this type of sorting on mongodb by using mongoose? I really don't want to make any operations on the code after fetching data.
推荐答案
您可以尝试使用本机JavaScript cursor.toArray()
方法:
You could try running a custom comparator function with the native JavaScript sort()
method on the array returned from the cursor.toArray()
method:
var order = ["food", "coffee", "grocery"];
var docs = db.collection.find().toArray().sort(function(a, b) {
return order.indexOf(a.category) - order.indexOf(b.category);
});
printjson(docs);
示例输出
[
{
"_id" : "4JW7miNITl",
"category" : "food"
},
{
"_id" : "4Je4kmrrbZ",
"category" : "coffee"
},
{
"_id" : "4JgAh3N86x",
"category" : "coffee"
},
{
"_id" : "4JEEuhNIae",
"category" : "grocery"
}
]
使用新的MongoDB 3.4版本,您应该能够利用本机MongoDB运算符 $indexOfArray
在聚合框架中.
With the new MongoDB 3.4 version, you should be able to leverage the use of the native MongoDB operators $addFields
and $indexOfArray
in the aggregation framework.
-
$addFields
管道步骤可让您$project
在现有文档中添加新字段,而不知道所有其他现有字段. -
$indexOfArray
表达式返回特定元素在给定数组中的位置.
- The
$addFields
pipeline step allows you to$project
new fields to existing documents without knowing all the other existing fields. - The
$indexOfArray
expression returns position of particular element in a given array.
因此,完全可以尝试以下聚合操作(使用MongoDB 3.4):
So putting that altogether you could try the following aggregate operation (with MongoDB 3.4):
var order = ["food", "coffee", "grocery"],
projection = {
"$addFields" : {
"__order" : { "$indexOfArray" : [ order, "$category" ] }
}
},
sort = { "$sort" : { "__order" : 1 } };
db.collection.aggregate([ projection, sort]);
这篇关于如何在mongo中按任意列表对对象数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!