1

冗長なデータを持つコレクションがあります。

サンプルデータ:

{
    unique_index : "1"
    other_field : "whatever1"
},
{
    unique_index : "2"
    other_field : "whatever2"
},
{
    unique_index : "1"
    other_field : "whatever1"
}

クエリを実行しました:(allowDiskUse:trueデータが多いため使用する必要があります)

db.collection.aggregate([
    {
        $group: { 
            _id: "$unique_index", 
            count: { $sum: 1 }
        } 
    }, 
    { $match: { count: { $gte: 2 } } }
], { allowDiskUse: true })

この出力が得られます:(たとえば)

{ "_id" : "1", "count" : 2 }
.
.

ここでの問題は、データを 1 つだけ保持したいということです。冗長データをすべて削除したい。100,000 件を超えるレコードなど、大量のデータがあることに注意してください。Ruby on Railsを使用しているため、mongodbまたはRoRで迅速かつ簡単なソリューションを探しています。

4

1 に答える 1

1

気にしない場合_id、最も簡単な方法は、個別のドキュメントを選択して新しいコレクションに入れ、名前を変更することです。

db.collection.aggregate([
    {$group: {
        _id: "$unique_index", 
        other_field: {$first: "$other_field"}
    }},
    {$project: {
        _id: 0,
        unique_index: "$_id",
        other_field:1
    }},
    {$out: "new_collection"}
]);

db.new_collection.renameCollection("collection", true);

すべてのインデックスを復元する必要があることに注意してください。またrenameCollection、シャードされたコレクションにも取り組んでいません。

于 2016-09-28T14:24:05.130 に答える