β

Answer by zangw for MongoDB - for each on aggregat

User zangw - Stack Overflow 35 阅读

Find the id of removed documents through aggregation in this way, then remove the document through _id ,

var cursor = db.History.aggregate([
      // sort the sessionId and timeCreated in desc order
      {$sort: {'sessionId': 1, timeCreated: -1}},
      { $group: {
           _id: { name: "$sessionId" },  
           uniqueIds: { $addToSet: "$_id" },
           count: { $sum: 1 } 
      } }, 
      // filter the duplicate documents
      { $match: { count: { $gte: 2 }}},
      // remove the youngest document id from `uniqueIds`
      { $project: {
            removeIds: {$slice: ['$uniqueIds', 
, 
                                 {$size: '$uniqueIds'}
                       ]}
      }}}]);
cursor.forEach(function(ret){
    ret.removeIds.forEach(function(id) {
        // remove the old duplicate document by _id
        db.History.remove({_id: id});
    }); 
});
作者:User zangw - Stack Overflow
most recent 30 from stackoverflow.com
原文地址:Answer by zangw for MongoDB - for each on aggregat, 感谢原作者分享。

发表评论