如何删除MongoDB中列表中的重复值?
您可以将聚合框架与$setUnion运算符一起使用。让我们首先创建一个包含文档的集合-
> db.removeDuplicatesDemo.insertOne({"InstructorName":"Chris","InstructorAge":34,"InstructorSubject": ["Java","C","Java","C++","MongoDB","MySQL","MongoDB"]}); { "acknowledged" : true, "insertedId" : ObjectId("5cb9d96c895c4fd159f80807") }
以下是在find()方法的帮助下显示集合中所有文档的查询-
> db.removeDuplicatesDemo.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5cb9d96c895c4fd159f80807"), "InstructorName" : "Chris", "InstructorAge" : 34, "InstructorSubject" : [ "Java", "C", "Java", "C++", "MongoDB", "MySQL", "MongoDB" ] }
以下是删除MongoDB列表中重复值的查询-
> db.removeDuplicatesDemo.aggregate([ ... { "$project": { ... "InstructorName":1, ... "InstructorAge" :1, ... "InstructorSubject" :{ "$setUnion": [ "$InstructorSubject", [] ] } ... }} ... ]).pretty();
这将产生以下输出-
{ "_id" : ObjectId("5cb9d96c895c4fd159f80807"), "InstructorName" : "Chris", "InstructorAge" : 34, "InstructorSubject" : [ "C", "C++", "Java", "MongoDB", "MySQL" ] }