arrays - MongoDB:如何计算键中值的数量
问题描述
我对 MongoDB 很陌生,我需要帮助弄清楚如何对 MongoDB 中的键执行聚合并使用该结果返回匹配项。
例如,如果我有一个名为 Fruits 的集合,其中包含以下文档:
{
"id": 1,
"name": "apple",
"type": [
"Granny smith",
"Fuji"
]
}, {
"id": 2,
"name": "grape",
"type": [
"green",
"black"
]
}, {
"id": 3,
"name": "orange",
"type": [
"navel"
]
}
我如何编写一个查询来返回两种类型的水果名称,即苹果和葡萄?
谢谢!
解决方案
演示 - https://mongoplayground.net/p/ke3VJIErhvb
使用$size获取类型为 2 的记录
$size 运算符匹配具有参数指定的元素数量的任何数组。例如:
db.collection.find({
type: { "$size": 2 } // match document with type having size 2
},
{ name: 1 } // projection to get name and _id only
)
推荐阅读
- google-cloud-platform - 有没有办法在 Google Cloud Platform 中安排 Cloud Shell 命令?
- database - Laravel 数据透视表插入数组
- swift - 如何快速将一个视图控制器值发送到另一个视图控制器表视图?
- sql - 诊断 DELETE 上的引用完整性错误的原因
- linux - 在 Windows bat 文件中运行 cygwin 命令
- docker - 如何列出 docker 容器中的所有目录和文件?
- swift - 在 swift 包管理器中为 API 调用编写单元测试
- python - 在调试模式下运行 Flask 应用程序不提供 IP 或调试器 PIN 或任何请求详细信息
- apache - .htaccess - 代码块的顺序是否起作用?
- sql-server - 在另一台 PC 上使用 SQL Server 数据库运行我的 WinForms 项目