mongodb - 如何仅获取 mongodb 中具有 3 个不同值的文档?
问题描述
我在 mongodb 中有以下数据:
{
"_id" : ObjectId("111"),
"id" : "111",
"classification" : [
{
"annotator" : "annotatorName1",
"category" : "white"
},
{
"annotator" : "annotatorName2",
"category" : "white"
},
{
"annotator" : "annotatorName3",
"category" : "black"
}
]
}
{
"_id" : ObjectId("222"),
"id" : "222",
"classification" : [
{
"annotator" : "annotatorName1",
"category" : "white"
},
{
"annotator" : "annotatorName2",
"category" : "blue"
},
{
"annotator" : "annotatorName3",
"category" : "black"
}
]
}
{
"_id" : ObjectId("333"),
"kind" : "youtube#video",
"etag" : "tagvalue",
"id" : "333"
}
请注意,classification
标签并不存在于我的所有记录中,如 id 为“333”的记录所示。
我需要从我的数据库中获取所有具有不同category
值的记录。所以,我需要一个查询,当我运行它时,我只会得到具有classification
标签的记录,并且恰好有 3 个不同 category
的值,在这种情况下,我想要一个只会返回给我的查询:
{
"_id" : ObjectId("222"),
"id" : "222",
"classification" : [
{
"annotator" : "annotatorName1",
"category" : "white"
},
{
"annotator" : "annotatorName2",
"category" : "blue"
},
{
"annotator" : "annotatorName3",
"category" : "black"
}
]
}
我应该在终端中输入什么命令才能获取在IFF存在下具有3 个唯一 category
值的所有记录?classification
classification
感谢您的帮助。
解决方案
以下聚合可用于找出恰好具有 3 个唯一类别的“id”:
db.collectionName.aggregate([
{$match : {classification : {$exists : true}}},
{$unwind: "$classification"},
{$group: { _id: "$id", uniqueCategories: {$addToSet: "$classification.category"}}},
{$project: {_id : 1, numberOfCategories: {$size: "$uniqueCategories"}} },
{$match: {numberOfCategories: 3} }
])
说明:我们从匹配具有分类元素的文档开始。然后我们 $unwind 它以便将嵌入的数组解构为单独的文档。然后它按 id 分组,并使用$addToSet
类别被收集到一个数组中——这将消除任何欺骗。然后我们将其投影$size
并匹配“等于 3”。
此聚合将生成 _id 设置为集合中具有 3 个唯一类别的文档的 id 字段的文档,您可以使用它们来获取文档。如果您的集合规模很大,您应该考虑$match
在开始时添加另一个阶段以限制数据集。就目前而言,它将进行集合扫描。
推荐阅读
- java - 如何将颜色设置为 JFrame
- php - Cronjob wget 只发布第一个变量
- typescript - 如何在 Typescript 中输入匹配/折叠功能
- xcode - 为版本 12 中的 Xcode 组织名称设置默认值
- python - 亮化 HSV 图像中的暗片
- reactjs - 反应导航 goBack() 并设置父状态
- python - Visual Studio Code 中的 IntelliSense 不适用于 python 包
- javascript - Javascript,检测是文本实际上未选中
- cytoscape.js - 从一个节点拖动到另一个节点时,Cytoscape 边缘处理重影预览显示“未定义”
- python - 如何删除以数字为索引名称的列?