作为聚合管道的一部分,我想将一个新字段转换到文档中,该字段是两个现有字段中的最小字段。
给定这样的文档:
{
_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”子文档显示文档的大小与 其他可能的尺寸。
我希望为文档累积一个排序分数,以显示它与一组参数的接近程度。如果我只是在寻找“大”文档,我可以这样做:
aggregate([
{$project: {"score": "$distances.big"}}
{$sort: {"score": 1}}
]);
但假设我想对“大”或“中”文档进行平均排序。我想要的是这样的:
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
}
]
关于mongodb - $project 一个新字段作为 mongodb 中两个字段的最小值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29810870/