【问题标题】:How to print count of duplicate documents in a Mongo collection? (Pymongo) [duplicate]如何打印 Mongo 集合中重复文档的数量? (Pymongo)[重复]
【发布时间】:2018-11-17 11:52:17
【问题描述】:

集合中的每个文档都是这样的。在这种情况下,A 和 C 都可以,但 B 有重复。

{
  "_id": {
    "$oid": "5bef93fc1c4b3236e79f9c25" # all these are unique
  },
  "Created_at": "Sat Nov 17 04:07:12 +0000 2018",
  "ID": {
    "$numberLong": "1063644700727480320" # duplicates identified by this ID
  },
  "Category": "A" #this is the category
}

{
  "_id": {
    "$oid": "5bef93531c4b3236e79f9c11"
  },
  "Created_at": "Sat Nov 17 05:17:12 +0000 2018",
  "ID": {
    "$numberLong": "1063644018276360192"
  },
  "Category": "B" 
}

{
  "_id": {
    "$oid": "5bef94e81c4b3236e79f9c3b"
  },
  "Created_at": "Sat Nov 17 05:17:12 +0000 2018",
  "ID": {
    "$numberLong": "1063644018276360192"
  },
  "Category": "B" 
}

{
  "_id": {
    "$oid": "5bef94591c4b3236e79f9cee" 
  },
  "Created_at": "Sat Nov 17 05:17:12 +0000 2018",
  "ID": {
    "$numberLong": "1063644700727481111"
  },
  "Category": "C" 
}

重复项由其 ID 定义。我想计算重复的数量并像这样打印它们的类别。

A 类:5(5 个重复标记为 A 类)

B 类:6

C 类:15

这是我尝试过的,但它没有打印任何内容。我已经在我的 Mongo 数据库中植入了重复项。

cursor = db.collection.aggregate([
    { 
        "$group": { 
            "_id": {"ID": "$ID"}, 
            "uniqueIds": { "$addToSet": "$_id" },
            "count": { "$sum": 1 } 
        }
    }, 
    { "$match": { "count": { "$gt": 1 } } }
])

for document in cursor:
    print(document)

感谢您的帮助 :)

【问题讨论】:

  • 它应该可以工作。可能您的计数不会大于($gt)1?试试这个db.collection.aggregate([ { "$group": { "_id": "$ID", "uniqueIds": { "$addToSet": "$Category" }, "count": { "$sum": 1 } }} ])
  • 感谢您的帮助。我已经尝试过您的代码,但它仍然无法正常工作。也没有错误。它什么也不打印。
  • 我添加了更多文档。
  • 看看mongoplayground.net/p/WtwN32is1G9。没事吧?
  • 是的,看起来不错,但我仍然无法打印输出。我需要打印 db.collection.aggregate

标签: python mongodb


【解决方案1】:

试试这个:

db.collection.aggregate([
{
    $group : {
                 "_id" : {"ID" : "$ID", "Category" : "$Category"}, 
                 "Count" : {$sum : 1}
             }
}, 
{
    $match : {
                 "Count" : {$gt : 1}
             }
}, 
{
    $project : {
                   "_id" : 0, 
                   "ID" : "$_id.ID", 
                   "Category" : "$_id.Category", 
                   "Count" : "$Count" 
                }
}
]);

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多