2015-11-10 52 views
0

在我們收集的多次出現,有結構,如:刪除同一對象

Object: //below is object metadata from mongo 
    _id 
    created_at 
    lang 
    source 
    object: //this is real object data from our db 
     id 
     created_at 
     object_class 

我跑下面的查詢在此集合:

db.getCollection('foo').aggregate(
    [ 
    { 
     $match: { 
      lang: 'bar', 
      pushed_at:{ 
      $gte: new ISODate("2015-11-09T00:00:00.000Z"), 
      $lt: new ISODate("2015-11-10T00:00:00.000Z") 
      } 
     } 
    }, 
    { 
     $group: { 
      _id: "$object.id", 
      occurences: {$sum: 1} 
     } 
    }, 
    { 
     $match: { 
      occurences: {$gt: 1} 
     } 
    } 
]) 

其中返回: Alt text

看樣子我們收集到的重複條目。重複我的意思是相同的對象Object.object.id。 我想使用我使用的agreggate函數的結果去除多餘的出現。 請注意,我不想刪除任何東西,只是冗餘的,所以以上彙總返回occurences: 1

如何做到這一點,也使用聚合結果?

+0

您可以編輯您的問題包括[最小,完整,可驗證的示例](http://stackoverflow.com/help/mcve) ,即一些樣本數據恰好足以產生期望的結果以及該樣本數據的預期輸出? – chridam

回答

1

我想你可以嘗試在shell:

db.foo.aggregate(
    [ 
    { 
     $match: { 
      lang: 'bar', 
      pushed_at:{ 
      $gte: new ISODate("2015-11-09T00:00:00.000Z"), 
      $lt: new ISODate("2015-11-10T00:00:00.000Z") 
      } 
     } 
    }, 
    { 
     $group: { 
      _id: "$object.id", 
      occurences: {$sum: 1} 
     } 
    }, 
    { 
     $match: { 
      occurences: {$gt: 1} 
     } 
    } 
]).result.forEach(function(x) { 
    if(x.occurences > 1) { 
     for(i=0;i<x.occurences - 1;i++) { 
      db.foo.remove({"object.id":x._id}, true); 
     } 
    } 
} 
); 
+1

謝謝!這有很大幫助! – ex3v

+0

很高興聽到它! –

+0

對不起側面的問題,但我想知道是否可以在以前的查詢結果中調用像find()這樣的方法? – ex3v