在MongoDB数组中查找重复值 [英] Finding duplicate values in a MongoDB array
本文介绍了在MongoDB数组中查找重复值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含以下格式条目的集合:
I have a collection containing entries in following format:
{
"_id" : ObjectId("5538e75c3cea103b25ff94a3"),
"userID" : "USER001",
"userName" : "manish",
"collegeIDs" : [
"COL_HARY",
"COL_MARY",
"COL_JOHNS",
"COL_CAS",
"COL_JAMES",
"COL_MARY",
"COL_MARY",
"COL_JOHNS"
]
}
我需要找出重复的CollegeID.因此,结果应为"COL_MARY","COL_JOHNS",并在可能的情况下提供重复计数.请提供一个mongo查询以找到它.
I need to find out the collegeIDs those are repeating. So the result should give "COL_MARY","COL_JOHNS" and if possible the repeating count. Please do give a mongo query to find it.
推荐答案
可能会有很多这样的文档,因此您需要根据ObjectId来获取.
Probably there would be many of these documents and thus you want it per ObjectId.
db.myCollection.aggregate([
{"$project": {"collegeIDs":1}},
{"$unwind":"$collegeIDs"},
{"$group": {"_id":{"_id":"$_id", "cid":"$collegeIDs"}, "count":{"$sum":1}}},
{"$match": {"count":{"$gt":1}}},
{"$group": {"_id": "$_id._id", "collegeIDs":{"$addToSet":"$_id.cid"}}}
])
这可能是您想要的,但不清楚您的问题:
This might be what you want to, not clear from your question:
db.myCollection.aggregate([
{"$match": {"userID":"USER001"}},
{"$project": {"collegeIDs":1, "_id":0}},
{"$unwind":"$collegeIDs"},
{"$group": {"_id":"$collegeIDs", "count":{"$sum":1}}},
{"$match": {"count":{"$gt":1}}},
])
这篇关于在MongoDB数组中查找重复值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文