我正在尝试汇总一组食谱。该集合中的每个食谱都有一个calories
字段,即一次服务中的卡路里量。我需要找到每1,2和3份最接近 1000 卡路里的食谱。我知道你不能像我在下面那样使用$ min运算符,但它只是在那里提出一个想法。
[
{
$project: {
recipe: "$$ROOT",
"caloriesInOneServing": "$calories",
"caloriesInTwoServings": {$multiply: ["$calories", 2.0]},
"caloriesInThereServings": {$multiply: ["$calories", 3.0]}
}
},
{
$project: {
recipe: 1,
"caloriesInOneServingDiff": {$subtract: ["$caloriesInOneServing", 1000],
"caloriesInTwoServingsDiff": {$subtract: ["$caloriesInTwoServings", 1000],
"caloriesInThereServingsDiff": {$subtract: ["$caloriesInThereServings", 1000]
}
},
{
$project: {
recipe: 1,
//how do i find the min value among given fields?
minDiff: {$min: [$caloriesInOneServingDiff, caloriesInTwoServingsDiff, caloriesInThereServingsDiff]
}
},
{
$sort: { minDiff: -1 }
}
]
答案 0 :(得分:0)
这可以通过条件减法来完成:
Int operator*(Int b) const{
return Int{value*b.value};
}
Int operator/(Int b) const{
return Int{value/b.value};
}
Int operator-(Int b) const{
return Int{value - b.value};
}
const Int& operator++() {
++value;
return *this;
}
Int operator--(int) {
Int copy{value};
value--;
return copy;
}
};
ostream& operator<<(ostream& out, Int x) {
out << x.value;
}
int main(){
int a = 11; Int A{11};
int b = 4; Int B{4};
cout << ++a / b * b-- - a << endl; // 0
cout << ++A / B * B-- - A << endl; // 4
}
示例:
[
{
$project: {
recipe: "$$ROOT",
"caloriesInOneServing": "$calories",
"caloriesInTwoServings": {$multiply: ["$calories", 2.0]},
"caloriesInThereServings": {$multiply: ["$calories", 3.0]}
}
},
{
$project: {
recipe: 1,
"caloriesInOneServingDiff": {$cond: [
{ $lt: ['$caloriesInOneServing', 1000] },
{ $subtract: [1000, '$caloriesInOneServing'] },
{ $subtract: ['$caloriesInOneServing', 1000] }
]},
"caloriesInTwoServingsDiff": {$cond: [
{ $lt: ['$caloriesInTwoServings', 1000] },
{ $subtract: [1000, '$caloriesInTwoServings'] },
{ $subtract: ['$caloriesInTwoServings', 1000] }
]},
"caloriesInThereServingsDiff": {$cond: [
{ $lt: ['$caloriesInThereServings', 1000] },
{ $subtract: [1000, '$caloriesInThereServings'] },
{ $subtract: ['$caloriesInThereServings', 1000] }
]}
}
},
{
$project: {
recipe: 1,
minDiff: {$min: [$caloriesInOneServingDiff, caloriesInTwoServingsDiff, caloriesInThereServingsDiff]
}
},
{
$sort: { minDiff: -1 }
}
]
条件减法后:
calories = 300
x2 = 600
x3 = 900
min = x3,最接近1000