如何在 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" ] }
广告