要检查数组中的重复项,请在MongoDB中使用Aggregate()。让我们创建一个包含文档的集合-
> db.demo756.insertOne({"SubjectName":["MySQL","MongoDB","Java"]}); { "acknowledged" : true, "insertedId" : ObjectId("5eb01e0d5637cd592b2a4add") } > db.demo756.insertOne({"SubjectName":["MongoDB","MySQL","MongoDB","C","C+","MySQL"]}); { "acknowledged" : true, "insertedId" : ObjectId("5eb01e2b5637cd592b2a4ade") }
在find()方法的帮助下显示集合中的所有文档-
> db.demo756.find();
这将产生以下输出-
{ "_id" : ObjectId("5eb01e0d5637cd592b2a4add"), "SubjectName" : [ "MySQL", "MongoDB", "Java" ] } { "_id" : ObjectId("5eb01e2b5637cd592b2a4ade"), "SubjectName" : [ "MongoDB", "MySQL", "MongoDB", "C", "C+", "MySQL" ] }
以下是检查数组中重复项的查询-
> db.demo756.aggregate([ ... {"$project": {"SubjectName":1}}, ... {"$unwind":"$SubjectName"}, ... {"$group": {"_id":{"_id":"$_id", "Name":"$SubjectName"}, "count":{"$sum":1}}}, ... {"$match": {"count":{"$gt":1}}}, ... {"$group": {"_id": "$_id._id", "SubjectName":{"$addToSet":"$_id.Name"}}} ... ])
这将产生以下输出-
{ "_id" : ObjectId("5eb01e2b5637cd592b2a4ade"), "SubjectName" : [ "MongoDB", "MySQL" ] }