【发布时间】: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 } }} ]) -
感谢您的帮助。我已经尝试过您的代码,但它仍然无法正常工作。也没有错误。它什么也不打印。
-
我添加了更多文档。
-
是的,看起来不错,但我仍然无法打印输出。我需要打印 db.collection.aggregate