首页 > 解决方案 > 如何仅获取 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值的所有记录?classificationclassification

感谢您的帮助。

标签: mongodbmongodb-query

解决方案


以下聚合可用于找出恰好具有 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在开始时添加另一个阶段以限制数据集。就目前而言,它将进行集合扫描。


推荐阅读