首页 > 解决方案 > mongo - 计数返回未找到文档而不是 0

问题描述

在 SQL 查询中

select count(*) from table where id=1

0如果没有任何具有此类 id 的记录,将返回结果。

我想得到完全相同的行为,但在 mongo 中。不幸的是我只能使用聚合函数。

我正在尝试这样的事情

db.collection.aggregate([
  {
    "$match": {
      "key": 1
    }
  },
  {
    $count: "s"
  }
])

它适用,但仅适用于具有key:1但当此键不存在时“找不到文档”的记录

标签: mongodb

解决方案


您可以使用此聚合查询$facet来创建两种可能的方式:如果文档存在或文档不存在。

  • 首先$facet创建两种方式
  • notFound路结果永远是{count: 0};进入found方式有match
  • 然后$replaceRoot合并结果以获得所需的值。
db.collection.aggregate([
  {
    "$facet": {
      "notFound": [
        {
          "$project": {
            "_id": 0,
            "count": {
              "$const": 0
            }
          }
        },
        {
          "$limit": 1
        }
      ],
      "found": [
        {
          "$match": {
            "key": 1
          }
        },
        {
          "$count": "count"
        }
      ]
    }
  },
  {
    "$replaceRoot": {
      "newRoot": {
        "$mergeObjects": [
          {
            "$arrayElemAt": [
              "$notFound",
              0
            ]
          },
          {
            "$arrayElemAt": [
              "$found",
              0
            ]
          }
        ]
      }
    }
  }
])

此处存在密钥的示例和此处不存在密钥的示例。

我也用这个代替测试过,看起来$ifNull$mergeObjects可以。


推荐阅读