MongoDB: use $sum with multiple $cond



我想根据数组元素的大小计算点。我可以用$sum和多个$cond?

像这样:

{
$project: {
points: {
$sum: [
{
$cond: [
{
$and: [{ $gt: [{ $arrayElemAt: ["$matches", 0] }, 0] }, { $gt: [{ $arrayElemAt: ["$matches", 1] }, 0] }, { $gt: [{ $arrayElemAt: ["$matches", 2] }, 0] }],
},
10,
0,
],
},
{
$cond: [
{
$and: [{ $gt: [{ $arrayElemAt: ["$matches", 3] }, 0] }, { $gt: [{ $arrayElemAt: ["$matches", 4] }, 0] }, { $gt: [{ $arrayElemAt: ["$matches", 5] }, 0] }],
},
10,
0,
],
},
],
},
},
},

这个脚本总是返回20,即使不是所有条件都为真

文档示例:

{ 
"_id" : NumberInt(5), 
"total_matches" : NumberInt(0), 
"matches" : [
[
], 
[
], 
[
], 
[
], 
[
], 
[
], 
[
], 
[
], 
[
]
]

}

输出
{ 
"_id" : NumberInt(5), 
"points" : 20.0, 
"matches" : [
[
], 
[
], 
[
], 
[
], 
[
], 
[
], 
[
], 
[
], 
[
]
]
}

好的,问题是我在查询中忘记了$size。正确的查询是这样的:

{
$project: {
points: {
$sum: [
{
$cond: [
{
$and: [{ $gt: [{ $size:{ $arrayElemAt: ["$matches", 0] }}, 0] }, { $gt: [{ $arrayElemAt: ["$matches", 1] }, 0] }, { $gt: [{ $arrayElemAt: ["$matches", 2] }, 0] }],
},
10,
0,
],
},
{
$cond: [
{
$and: [{ $gt: [{ $size:{ $arrayElemAt: ["$matches", 3] }}, 0] }, { $gt: [{ $arrayElemAt: ["$matches", 4] }, 0] }, { $gt: [{ $arrayElemAt: ["$matches", 5] }, 0] }],
},
10,
0,
],
},
],
},
},
}

相关内容

  • 没有找到相关文章

最新更新