mongodb - mongo - 计数返回未找到文档而不是 0
问题描述
在 SQL 查询中
select count(*) from table where id=1
0
如果没有任何具有此类 id 的记录,将返回结果。
我想得到完全相同的行为,但在 mongo 中。不幸的是我只能使用聚合函数。
我正在尝试这样的事情
db.collection.aggregate([
{
"$match": {
"key": 1
}
},
{
$count: "s"
}
])
它适用,但仅适用于具有key:1
但当此键不存在时“找不到文档”的记录
解决方案
您可以使用此聚合查询$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
可以。
推荐阅读
- python - Heroku 与 Django、Celery 和 CloudAMPQ - 超时错误
- swift - 如何以通用格式编写可编码
- php - 使用 php 在 AWS QLDB 中提交事务时如何获取/计算 CommitDigest?
- php - 我们如何使用 PHP Wordpress 从后端启用和禁用必填字段属性
- azure - 比较两个 Azure 函数应用的应用程序设置
- swift - 如何从特定索引的字符串中快速删除某个长度的子字符串
- python - 包含某些元组的元组的元组索引列表
- android - api 监听器太多。有什么办法可以整齐的组织起来吗?
- node.js - 在 git bash 中使用 utf-8 的 npx 包
- google-cloud-platform - GCP 通知通道