【问题标题】:Count of MongoDB aggregation match resultsMongoDB 聚合匹配结果计数
【发布时间】:2018-09-26 05:58:44
【问题描述】:

我正在使用具有大量重复键的 MongoDB 集合。我定期进行聚合查询以找出这些重复项是什么,以便我可以深入研究并找出它们的不同之处。

不幸的是,数据库很大,而且经常是故意重复的。我想做的是找到具有重复项的 count 键,而不是打印具有数千行输出的结果。这可能吗?

(旁注:我通过 shell 进行所有查询,因此不需要外部工具或大量代码的解决方案将是首选,但我知道这并不总是可行的。)

示例记录:

{ "_id" : 1, "type" : "example", "key" : "111111", "value" : "abc" }
{ "_id" : 2, "type" : "example", "key" : "222222", "value" : "def" }
{ "_id" : 3, "type" : "example", "key" : "222222", "value" : "ghi" }
{ "_id" : 4, "type" : "example", "key" : "333333", "value" : "jkl" }
{ "_id" : 5, "type" : "example", "key" : "333333", "value" : "mno" }
{ "_id" : 6, "type" : "example", "key" : "333333", "value" : "pqr" }
{ "_id" : 7, "type" : "example", "key" : "444444", "value" : "stu" }
{ "_id" : 8, "type" : "example", "key" : "444444", "value" : "vwx" }
{ "_id" : 9, "type" : "example", "key" : "444444", "value" : "yz1" }
{ "_id" : 10, "type" : "example", "key" : "444444", "value" : "234" }

这是我一直用来根据key 查找重复项的查询:

db.collection.aggregate([
    {
        $match: {
            type: "example"
        }
    },
    {
        $group: {
            _id: "$key",
            count: {
                $sum: 1
            }
        }
    },
    {
        $match: {
            count: {
                $gt: 1
            }
        }
    }
])

这给了我一个输出:

{
  "_id": "222222",
  "count": 2
},
{
  "_id": "333333",
  "count": 3
},
{
  "_id": "444444",
  "count": 4
}

我想要得到的结果:

3

【问题讨论】:

  • 在 $match 之后添加{$count:"count"}。
  • @Veeram 谢谢!

标签: mongodb mongodb-query aggregation-framework


【解决方案1】:

你快到了,只是错过了最后一个$count

db.collection.aggregate([
  {
    $match: {
      type: "example"
    }
  },
  {
    $group: {
      _id: "$key",
      count: {
        $sum: 1
      }
    }
  },
  {
    $match: {
      count: {
        $gt: 1
      }
    }
  },
  {
    $count: "count"
  }
])

【讨论】:

  • 非常感谢!这似乎是正确的解决方案,但显然我们仍在使用 MongoDB v3.2,并且在尝试使用它时出现错误。我找到了同事给我的另一种(更老套的)方法。我会把它作为另一个解决方案发布。
【解决方案2】:

Akrion's answer 似乎是正确的,但我无法测试它,因为我们使用的是旧版本的 MongoDB。一位同事给了我一个适用于 3.2 的替代解决方案(不确定其他版本)。

添加.toArray()会将结果转换为数组,然后您可以使用.length获取数组的大小。

db.collection.aggregate([
    {
        $match: {
            type: "example"
        }
    },
    {
        $group: {
            _id: "$key",
            count: {
                $sum: 1
            }
        }
    },
    {
        $match: {
            count: {
                $gt: 1
            }
        }
    }
]).toArray().length

【讨论】:

  • 这是个坏主意。您只需要文件总数。但是,通过上述方式,您会收到不需要的文件。
  • 不,我需要的是单个 $match 阶段后重复键的总数。在了解了有关 MongoDB 的更多信息后,我正在审查这个和接受的答案,它们对我的情况是正确的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-29
  • 2019-01-24
  • 1970-01-01
  • 1970-01-01
  • 2021-04-25
相关资源
最近更新 更多