在MongoDB 3.x中如何删除重复记录?
要删除重复的记录,请使用aggregate()。让我们创建一个包含文档的集合-
> db.demo438.insertOne({"FirstName":"Chris"}); { "acknowledged" : true, "insertedId" : ObjectId("5e775c37bbc41e36cc3caea1") } > db.demo438.insertOne({"FirstName":"David"}); { "acknowledged" : true, "insertedId" : ObjectId("5e775c3dbbc41e36cc3caea2") } > db.demo438.insertOne({"FirstName":"Chris"}); { "acknowledged" : true, "insertedId" : ObjectId("5e775c40bbc41e36cc3caea3") } > db.demo438.insertOne({"FirstName":"Bob"}); { "acknowledged" : true, "insertedId" : ObjectId("5e775c44bbc41e36cc3caea4") } > db.demo438.insertOne({"FirstName":"David"}); { "acknowledged" : true, "insertedId" : ObjectId("5e775c47bbc41e36cc3caea5") }
在find()方法的帮助下显示集合中的所有文档-
> db.demo438.find();
这将产生以下输出-
{ "_id" : ObjectId("5e775c37bbc41e36cc3caea1"), "FirstName" : "Chris" } { "_id" : ObjectId("5e775c3dbbc41e36cc3caea2"), "FirstName" : "David" } { "_id" : ObjectId("5e775c40bbc41e36cc3caea3"), "FirstName" : "Chris" } { "_id" : ObjectId("5e775c44bbc41e36cc3caea4"), "FirstName" : "Bob" } { "_id" : ObjectId("5e775c47bbc41e36cc3caea5"), "FirstName" : "David" }
以下是删除MongoDB3.x中重复记录的查询-
> db.demo438.aggregate([ { "$group":{ _id:{FirstName:"$FirstName"}, DuplicateValueIds:{$addToSet:"$_id"} } } ]);
这将产生以下输出-
{ "_id" : { "FirstName" : "David" }, "DuplicateValueIds" : [ ObjectId("5e775c47bbc41e36cc3caea5"), ObjectId("5e775c3dbbc41e36cc3caea2") ] } { "_id" : { "FirstName" : "Bob" }, "DuplicateValueIds" : [ ObjectId("5e775c44bbc41e36cc3caea4") ] } { "_id" : { "FirstName" : "Chris" }, "DuplicateValueIds" : [ ObjectId("5e775c40bbc41e36cc3caea3"), ObjectId("5e775c37bbc41e36cc3caea1") ] }