2017-05-09 137 views
0

樣本數據:在Mongodb中獲取唯一文檔?

{"_id" : ObjectId("58bd10e4ff1743c527754160"), 
     "data" : [ 
      { 
       "No" : "70", 
       "Type" : "82", 
       "Device" : "01", 
       "timestamp" : "2017-03-06 13:00:32" 
       }] 
    }, 
    {"_id" : ObjectId("58bd10sdfe4ff1743csdf0754"), 
     "data" : [ 
      { 
       "No" : "75", 
       "Type" : "22", 
       "Device" : "02", 
       "timestamp" : "2017-03-06 13:00:32" 
       }] 
    } 

我有有相同的時間戳一些文件,所以我想找到只時間戳的基礎上獨一無二的文件。 我已經做了不同的時間戳,但我想要完整的文檔。

想要的輸出: 如果有相同的時間戳,我只想要一個文檔。

回答

1
You will only get one output if you run this query. 

db.getCollection('tests').aggregate([{$match:{"data.timestamp":"2017-03-06 13:00:32"}},{$limit:1}]) 
+0

thnaks,現在我想刪除重複的一個。 –

+0

使用相同的聚合函數來獲取一個結果文檔,然後使用remove函數刪除該文檔。@ TB.M –

1

解決方案1:

db.your_collection.aggregate([ 
    { 
     $group:{ 
     _id:"$data.timestamp", 
     data:{ 
      $first:"$data" 
     } 
     } 

} ])

這會給你以下幾點:

{ "_id" : [ "2017-03-06 13:00:32" ], "data" : [ { "No" : "70", "Type" : "82", "Device" : "01", "timestamp" : "2017-03-06 13:00:32" }, { "No" : "10", "Type" : "20", "Device" : "01", "timestamp" : "2018-02-04 10:00:00" } ] } 

解決方案2:

db.your_collection.aggregate([ 
    { $unwind : '$data'}, 
    { $group : { 
     _id : '$data.timestamp', 
     'No': { $first : '$data.No'}, 
     'Type': { $first : '$data.Type'}, 
     'Device': { $first : '$data.Device'}, 
     'timestamp': { $first : '$data.timestamp'}, 
     } 
    } 
]); 

這會給你以下幾點:

[ 
    { "_id" : "2017-03-06 13:00:32", "No" : "70", "Type" : "82", "Device" : "01", "timestamp" : "2017-03-06 13:00:32" }, 
    { "_id" : "2018-02-04 10:00:00", "No" : "10", "Type" : "20", "Device" : "01", "timestamp" : "2018-02-04 10:00:00" }, 
] 
+0

非常感謝,並且不管重複如何刪除它? –