$project 一个新字段作为 mongodb 中两个字段中的最小值

use*_*461 4 mongodb aggregation-framework

作为聚合管道的一部分,我想将一个新字段投影到文档上,该文档是两个现有字段中的最小值。

鉴于这样的文件:

{
    _id: "big1",
    size: "big",
    distances: { big: 0, medium: 0.5, small: 1 }
}
{
    _id: "med1",
    size: "medium",
    distances: { big: 0.5, medium: 0, small: 0.5 }
}
{
    _id: "small1",
    size: "small",
    distances: { big: 1, medium: 0.5, small: 0 }
}
Run Code Online (Sandbox Code Playgroud)

“距离”子文档显示文档大小与其他可能大小的“距离”。

我希望积累文档的排序分数,以显示它与一组参数的接近程度。如果我只是寻找“大”文档,我可以这样做:

aggregate([
    {$project: {"score": "$distances.big"}}
    {$sort: {"score": 1}}
]);
Run Code Online (Sandbox Code Playgroud)

但假设我想对“大”或“中”文档进行同等排序。我想要的是这样的:

aggregate([
    {$project: {"score": {$min: ["$distances.big", "$distances.medium"]}}},
    {$sort: {"score": 1}}
])
Run Code Online (Sandbox Code Playgroud)

但这不起作用,因为 $min 仅对 $group 查询中的相邻文档进行操作。

有没有办法将两个现有字段中的最小值投影为排序参数?

Joh*_*yHK 5

您可以使用$cond运算符执行比较,以使用运算符找到最小值$lt

db.test.aggregate([
    {$project: {score: {$cond: [
        {$lt: ['$distances.big', '$distances.medium']}, // boolean expression
        '$distances.big',   // true case
        '$distances.medium' // false case
    ]}}},
    {$sort: {score: 1}}
])
Run Code Online (Sandbox Code Playgroud)

结果:

[ 
    {
        "_id" : "big1",
        "score" : 0
    }, 
    {
        "_id" : "med1",
        "score" : 0
    }, 
    {
        "_id" : "small1",
        "score" : 0.5
    }
]
Run Code Online (Sandbox Code Playgroud)