如何在 mongo 集合中查找重复字段。
我想检查是否有任何“名称”字段重复。
{
"name" : "ksqn291",
"__v" : 0,
"_id" : ObjectId("540f346c3e7fc1054ffa7086"),
"channel" : "Sales"
}
非常感谢!
最佳答案
在 name
上使用聚合并使用 count > 1
获取 name
:
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”
https://stackoverflow.com/questions/26984799/