我如何在mongo集合中找到重复的字段。
我想检查是否有任何“name”字段是重复的。
{
"name" : "ksqn291",
"__v" : 0,
"_id" : ObjectId("540f346c3e7fc1054ffa7086"),
"channel" : "Sales"
}
很多谢谢!
我如何在mongo集合中找到重复的字段。
我想检查是否有任何“name”字段是重复的。
{
"name" : "ksqn291",
"__v" : 0,
"_id" : ObjectId("540f346c3e7fc1054ffa7086"),
"channel" : "Sales"
}
很多谢谢!
当前回答
在名称上使用聚合,并使用计数>获取名称1:
db.collection.aggregate([
{"$group" : { "_id": "$name", "count": { "$sum": 1 } } },
{"$match": {"_id" :{ "$ne" : null } , "count" : {"$gt": 1} } },
{"$project": {"name" : "$_id", "_id" : 0} }
]);
按重复数从多到少对结果进行排序:
db.collection.aggregate([
{"$group" : { "_id": "$name", "count": { "$sum": 1 } } },
{"$match": {"_id" :{ "$ne" : null } , "count" : {"$gt": 1} } },
{"$sort": {"count" : -1} },
{"$project": {"name" : "$_id", "_id" : 0} }
]);
要使用除“name”以外的其他列名,请将“$name”更改为“$column_name”
其他回答
这就是我们如何在mongoDB compass中实现这一点
在Compass Mongo数据库中使用$sortByCount搜索重复 (截图):https://i.stack.imgur.com/L85QV.png
如果有人在寻找带有额外的"$and" where子句的重复查询,比如"and where someOtherField is true"
诀窍是从另一个$match开始,因为分组之后就不再有所有可用的数据了
// Do a first match before the grouping
{ $match: { "someOtherField": true }},
{ $group: {
_id: { name: "$name" },
count: { $sum: 1 }
}},
{ $match: { count: { $gte: 2 } }},
我找了很长时间才找到这个符号,希望我能帮助有同样问题的人
在名称上使用聚合,并使用计数>获取名称1:
db.collection.aggregate([
{"$group" : { "_id": "$name", "count": { "$sum": 1 } } },
{"$match": {"_id" :{ "$ne" : null } , "count" : {"$gt": 1} } },
{"$project": {"name" : "$_id", "_id" : 0} }
]);
按重复数从多到少对结果进行排序:
db.collection.aggregate([
{"$group" : { "_id": "$name", "count": { "$sum": 1 } } },
{"$match": {"_id" :{ "$ne" : null } , "count" : {"$gt": 1} } },
{"$sort": {"count" : -1} },
{"$project": {"name" : "$_id", "_id" : 0} }
]);
要使用除“name”以外的其他列名,请将“$name”更改为“$column_name”
例如,当您想创建一个不区分大小写的索引时,有时您希望无论大小写都能找到重复项。在这种情况下,您可以使用这个聚合管道
db.collection.aggregate([
{'$group': {'_id': {'$toLower': '$name'}, 'count': { '$sum': 1 }, 'duplicates': { '$push': '$$ROOT' } } },
{'$match': { 'count': { '$gt': 1 } }
]);
解释:
按名称分组,但首先将大小写改为小写,并将docs推到duplicate数组中。 匹配那些记录大于1的组(重复项)。