我如何在mongo集合中找到重复的字段。
我想检查是否有任何“name”字段是重复的。
{
"name" : "ksqn291",
"__v" : 0,
"_id" : ObjectId("540f346c3e7fc1054ffa7086"),
"channel" : "Sales"
}
很多谢谢!
我如何在mongo集合中找到重复的字段。
我想检查是否有任何“name”字段是重复的。
{
"name" : "ksqn291",
"__v" : 0,
"_id" : ObjectId("540f346c3e7fc1054ffa7086"),
"channel" : "Sales"
}
很多谢谢!
当前回答
例如,当您想创建一个不区分大小写的索引时,有时您希望无论大小写都能找到重复项。在这种情况下,您可以使用这个聚合管道
db.collection.aggregate([
{'$group': {'_id': {'$toLower': '$name'}, 'count': { '$sum': 1 }, 'duplicates': { '$push': '$$ROOT' } } },
{'$match': { 'count': { '$gt': 1 } }
]);
解释:
按名称分组,但首先将大小写改为小写,并将docs推到duplicate数组中。 匹配那些记录大于1的组(重复项)。
其他回答
如果您有一个大型数据库,并且属性名只出现在一些文档中,anhic给出的答案可能非常低效。
为了提高效率,您可以向聚合添加$匹配。
db.collection.aggregate(
{"$match": {"name" :{ "$ne" : null } } },
{"$group" : {"_id": "$name", "count": { "$sum": 1 } } },
{"$match": {"count" : {"$gt": 1} } },
{"$project": {"name" : "$_id", "_id" : 0} }
)
另一种选择是使用$sortByCount阶段。
db.collection.aggregate([
{ $sortByCount: '$name' }
]
这是$group & $sort的组合。
$sortByCount阶段相当于以下$group + $sort序列: {$组:{_id: <表达式>,数:{$金额:1}}}, {$sort: {count: -1}}
如果你需要查看所有复制的行:
db.collection.aggregate([
{"$group" : { "_id": "$name", "count": { "$sum": 1 },"data": { "$push": "$$ROOT" }}},
{"$unwind": "$data"},
{"$match": {"_id" :{ "$ne" : null } , "count" : {"$gt": 1} } },
]);
db.getCollection('orders').aggregate([
{$group: {
_id: {name: "$name"},
uniqueIds: {$addToSet: "$_id"},
count: {$sum: 1}
}
},
{$match: {
count: {"$gt": 1}
}
}
])
第一组根据字段查询分组。
然后我们检查唯一Id并对其计数,如果count大于1,则该字段在整个集合中是重复的,因此将由$match query处理。
例如,当您想创建一个不区分大小写的索引时,有时您希望无论大小写都能找到重复项。在这种情况下,您可以使用这个聚合管道
db.collection.aggregate([
{'$group': {'_id': {'$toLower': '$name'}, 'count': { '$sum': 1 }, 'duplicates': { '$push': '$$ROOT' } } },
{'$match': { 'count': { '$gt': 1 } }
]);
解释:
按名称分组,但首先将大小写改为小写,并将docs推到duplicate数组中。 匹配那些记录大于1的组(重复项)。