我有一个如下所示的mongoDB集合。如您所见,它有许多重复的记录,也许有一些不同的属性。现在,我的收藏夹中有18000个结果,我需要删除其中的所有重复项。不管我保留哪一个,我都不需要骗子。谁能帮我或指出正确的方向? MongoDB的新手。
提前致谢
{
commonName: "Lionel Messi",
firstName: "Lionel",
lastName: "Messi",
rating: 97
},{
commonName: "Lionel Messi",
firstName: "Lionel",
lastName: "Messi",
rating: 96
},{
commonName: "Lionel Messi",
firstName: "Lionel",
lastName: "Messi",
rating: 92
},{
commonName: "Jamie Vardy",
firstName: "Jamie",
lastName: "Vardy",
rating: 82
},{
commonName: "Jamie Vardy",
firstName: "Jamie",
lastName: "Vardy",
rating: 86
}
最佳答案
您可以使用aggregate
清除数据,然后使用$out
编写集合,甚至覆盖当前集合:
db.players.aggregate([
{
$group : {
_id : { commonName: "$commonName" },
commonName: {$first: "$commonName"},
firstName: {$first: "$firstName"},
lastName: {$first: "$lastName"},
rating: {$first: "$rating"},
}
},
{ $project : { _id:0, commonName:1, firstName:1, lastName:1, rating:1 } },
{ $out : "players" }
])
注意:如果要编写新集合,请使用
{ $out : "newCollection" }