如何打印Mongo集合中重复文档的计数?(皮蒙戈)

2024-03-28 12:26:43 发布

您现在位置:Python中文网/ 问答频道 /正文

集合中的每个文档如下所示。在这种情况下,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)

感谢您的帮助:)


Tags: 文档idcount情况thisdocumentsatcursor
1条回答
网友
1楼 · 发布于 2024-03-28 12:26:43

试试这个:

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" 
                }
}
]);

希望这有帮助!你知道吗

相关问题 更多 >