mongodb去重操作只留一條
阿新 • • 發佈:2018-11-13
原表記錄:
需要把related_type=1 and action_type=3 並且related_id相同的刪掉一條。只留一個去重。
db.user_action_log.aggregate([
{$match:{related_type:1,action_type:3}}, (查詢條件)
{
$group: { _id: {related_id: '$related_id'},count: {$sum: 1},dups: {$addToSet: '$_id'}} (根據related_id分組,$group只會返回參與分組的欄位,使用$addToSet在返回結果陣列中增加_id欄位)
}, { $match: {count: {$gt: 1}} (匹配數量大於1的資料) }
]).forEach(function(doc){ (使用forEach迴圈根據_id刪除資料)
doc.dups.shift();
db.userInfo.remove({_id: {$in: doc.dups}});
})
刪除後資料:
db.user_action_log.aggregate([
{$match:{related_type:1,action_type:3}},
{
$group: { _id: {related_id: '$related_id'},count: {$sum: 1},dups: {$addToSet: '$_id'}}
}, { $match: {count: {$gt: 1}} }
]).forEach(function(doc){
doc.dups.shift();
db.userInfo.remove({_id: {$in: doc.dups}});
})