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

$project a new field as the minimum of two fields in mongodb

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

给定这样的文档:

{
    _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 }
}

"distances" 子文档显示 "far" 文档的大小来自 其他可能的尺寸。

我希望为文档累积一个排序分数,以显示它与一组参数的接近程度。如果我只查找 "big" 个文档,我可以这样做:

aggregate([
    {$project: {"score": "$distances.big"}}
    {$sort: {"score": 1}}
]);

但假设我想对 "big" 或 "medium" 文档进行平均排序。我想要的是这样的:

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

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

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

您可以使用 $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}}
])

结果:

[ 
    {
        "_id" : "big1",
        "score" : 0
    }, 
    {
        "_id" : "med1",
        "score" : 0
    }, 
    {
        "_id" : "small1",
        "score" : 0.5
    }
]