mongodb - mongodb - 如果查询中的排序应该为零,则获得零差
问题描述
通常可以在客户端处理零和不存在的字段。在我的情况下,我需要它在 mongodb 查询的排序功能中使用。
这是我的查询:
{
"$group": {
"_id": "null",
"upCount": { "$sum": "$up" },
"downCount": { "$sum": "$down" }
},
},
{
$project: {
difference: { $subtract: ["$upCount", "$downCount"] },
// Add other keys in here as necessary
upCount: 1,
downCount: 1,
}
},
并且在排序中
.sort({ 'commentVotes.difference': -1 }
当存在 upCount 和 downCount 的值时,这非常有效。
问题是:当反对票多于赞成票时,我会遇到commentVotes.difference 可能为负数的情况。在这种情况下,投票数为零的评论即使在否定评论之后也会排在最后,因为它们不会返回零差值。
简而言之,下面的行如何返回一个0
when"$sum": "$up"
并且"$sum": "$down"
没有任何值的值?
difference: { $subtract: ["$upCount", "$downCount"] },
解决方案
您可以使用$ifNull
,如果值为 null (没有值),则使用0
db.collection.aggregate([
{
$project: {
difference: {
$subtract: [
{
$ifNull: [
"$upCount",
0
]
},
{
$ifNull: [
"$downCount",
0
]
}
]
}
}
}
])
推荐阅读
- c - CS50编码练习马里奥不太舒服
- dialogflow-es - 如何转到 Dialogflow 响应中的下一行
- python - PyCharm 调试器中的“测试”包中的绝对导入失败并出现 ModuleNotFoundError
- r - 如何使用 R 中的 TM 包将我的语料库元数据附加到我的 dtm 数据帧导出中
- google-chrome-extension - Chrome 扩展程序导致活动网站上的 div 出现不当行为
- javascript - JavaScript 在 for 循环中追加多个
- python - 将阈值逻辑应用于 NumPy 数组的一列
- reactjs - React Hooks createContext:当它是一个数组时如何更新UserContext?
- c# - C# API OAuth 消费
- javascript - RN perf 问题:尽早绑定,不要在渲染中创建函数