私はMongoデータベースに重複したエントリがたくさんあります。これらの複製を簡単に削除する方法はありますか? Iは、2つの異なるシナリオに興味:重複したエントリのフィールドの各々についてMongoDB:フィールドに基づいて重複を削除する
は重複したエントリのすべてのフィールドのサブセットのみについて
(オブジェクトIDを除く)等しい等しいです。この場合、これらのフィールドを指定してそれらに基づいて重複を削除したいと思います。
これを行う「モンゴルな」方法は何ですか?
例のエントリは次のようになります。それは「script.js」という名前のファイルにこれを書い使用する
var matchingId = [];
db.collectionName.aggregate([
{
// group stage: group document by field
// this return one document per unique value
$group:{
_id:{
category:"$category",
city:"$city"
// ...
// here add as many field as you want for duplicate check
},
// this field count the number of documents having the same
// values for the selected fields
count:{
$sum:1
},
// this field store the _id of documents that have the same
// value for selected fields
match:{
$push:"$_id"
}
}
},
{
// only keep documents where count > 1
$match:{
count:{
$gt:1
}
}
}],
{
// allow mongoDB to write to disk if your collection is too big
allowDiskUse: true
}
).forEach(function(doc) {
doc.match.shift(); // remove the first objectId
doc.match.forEach(function(duplicateId) {
matchingId.push(duplicateId);
});
});
// remove duplicate documents
db.collectionName.remove({_id: {$in: matchingId}})
:ここ
{
"_id" : ObjectId("57294d7071f55974cdae318e"),
"category" : "house",
"city" : "Boston",
"title" : "title here",
"url" : "http://url.com",
"text" : " some text here",
"time" : ISODate("2016-05-03T23:49:00Z"),
"user_online_since" : ISODate("2012-10-01T00:00:00Z"),
"price_eur" : 85000
}
を含むスクリプトを実行した後、対応する文書
を削除することができますので、他の_idsを保存するいくつかのサンプル文書とあなたは – felix