MongoDB:使用多个$ cond的$ sum
我希望计算基于数组元素的大小。 我可以使用多个$ cond的$ sum?
类似的内容:
{
$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" : [
[
],
[
],
[
],
[
],
[
],
[
],
[
],
[
],
[
]
]
}
I want calculate points based to the size of an array element.
I can use $sum with multiple $cond?
Something like this:
{
$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,
],
},
],
},
},
},
This script always returns 20 even if not all conditions are true
Example of document:
{
"_id" : NumberInt(5),
"total_matches" : NumberInt(0),
"matches" : [
[
],
[
],
[
],
[
],
[
],
[
],
[
],
[
],
[
]
]
}
OUTPUT
{
"_id" : NumberInt(5),
"points" : 20.0,
"matches" : [
[
],
[
],
[
],
[
],
[
],
[
],
[
],
[
],
[
]
]
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好的,问题是我在查询中忘记了$尺寸。
正确的查询是:
Ok, the problem is that I forgot $size in the query.
The right query is this: