首页 > 解决方案 > 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 可能为负数的情况。在这种情况下,投票数为零的评论即使在否定评论之后也会排在最后,因为它们不会返回零差值。

简而言之,下面的行如何返回一个0when"$sum": "$up"并且"$sum": "$down"没有任何值的值?

difference: { $subtract: ["$upCount", "$downCount"] },

标签: mongodb

解决方案


您可以使用$ifNull,如果值为 null (没有值),则使用0

db.collection.aggregate([
  {
    $project: {
      difference: {
        $subtract: [
          {
            $ifNull: [
              "$upCount",
              0
            ]
          },
          {
            $ifNull: [
              "$downCount",
              0
            ]
          }
        ]
      }
    }
  }
])

工作Mongo 游乐场


推荐阅读