mongodb-如果在查询中排序时应为零,则获得零的差值
通常零和不存在的字段可以在客户端处理。在我的情况下,我需要在mongodb查询的排序函数中使用它 我的问题是:mongodb-如果在查询中排序时应为零,则获得零的差值,mongodb,Mongodb,通常零和不存在的字段可以在客户端处理。在我的情况下,我需要在mongodb查询的排序函数中使用它 我的问题是: { "$group": { "_id": "null", "upCount": { "$sum": "$up" }, &qu
{
"$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 }
当存在“向上计数”和“向下计数”的值时,这种方法非常有效
问题是:我会遇到这样的情况:当反对票多于赞成票时,两者之间的差异可能为负。在这种情况下,投票数为零的评论被排在最后,甚至排在反对票之后,因为它们不会返回零的差值
简而言之,当“$sum”:“$up”
和“$sum”:“$down”
没有任何值时,下一行如何返回值0
difference: { $subtract: ["$upCount", "$downCount"] },
您可以使用
$ifNull
,如果值为null(没有任何值),则使用0
db.collection.aggregate([
{
$project: {
difference: {
$subtract: [
{
$ifNull: [
"$upCount",
0
]
},
{
$ifNull: [
"$downCount",
0
]
}
]
}
}
}
])
工作啊,回答得不错。我确实遇到了ifNull,我应该使用它。