猫鼬根据文档中的特定值对文档进行排序



我使用此语法过滤文档

const query = Model.find();
const filters = req.body;
if(filters.someValue){
query.find().where('someValue').eq(filters.someValie);
}
...(imagine 40 more)

在我执行这个查询以查找所有文档之前,我想按照特定的顺序对其进行排序,我将确定

if(filters.sort){
here the sort need to be applied - before execution.
}

我在DB中得到了一些带有四个可选值的字段,我想为每个值附加顺序(排序需要通过它来应用(。假设这些值可以是:

"A", "B", "C", "D"

我希望文件按以下顺序排序:

{value:"A",order:3}, {value:"B", order:2}, {value:"C", order:4}, {value:"D", order:1}

在应用排序之后,执行查询。问题是,我在网上找不到任何关于这方面的信息,我唯一尝试的东西(带排序和条件的聚合(也不起作用。代码:

SomeModel.aggregate([
{ "$project" : {
"document": "$$ROOT",
"order" : {
"$cond" : {
if : { "$eq" : ["$someField", "D"] }, then : 1,
else  : { "$cond" : {
"if" : { "$eq" : ["$someField", "B"] }, then : 2, 
else  : { "if" : { "$eq" : ["$someField", "A"]}, then: 3, 
else : { "if" : { "$eq" : ["$someField", "C"]}, then: 4
}
}
}
}
}
}
}}, 
{"$sort" : {"order" : 1} }
]);

这看起来像是内部if/then/elses格式错误的问题。实际上,在第三个和第四个else中缺少一些$cond运算符。因此,order属性(使用if/then/else而不是数字的对象(的值不正确。

这个版本适用于我:

[
{
$project: {
'document': '$$ROOT',
order: {
$cond: {
if: {'$eq': ['$someField', 'D']}, then: 1,
else: {
'$cond': {
'if': {'$eq': ['$someField', 'B']}, then: 2,
else: {
'$cond': {
'if': {'$eq': ['$someField', 'A']}, then: 3,
else: {
'$cond': {'if': {'$eq': ['$someField', 'C']}, then: 4, else: 5}
}
}
}
}
}
}
}
}
},
{$sort: {'order': 1}}
]

然而,在这种情况下,我认为$switch运算符可能更好,特别是如果您有更多可能的值(而不仅仅是这4个(。

aggregate([
{
$project: {
'document': '$$ROOT',
order: {
$switch: {
branches: [
{case: {'$eq': ['$name', 'D']}, then: 1},
{case: {'$eq': ['$name', 'B']}, then: 2},
{case: {'$eq': ['$name', 'A']}, then: 3},
{case: {'$eq': ['$name', 'C']}, then: 4},
],
default: null
}
}
}
},
{$sort: {'order': 1}}
])

我设法用另一种方法修复了它。当我在DB中插入文档时,我想要索引的每个字段都将有另一个字段来表示值的索引。(假设字段名称为course,其值为A、B、C、D-我将添加名为courseIndex的字段,并通过值-A=4、B=1、C=2、D=3映射索引(。

有了这个,我可以根据我的条件实现排序:(

最新更新