2016-11-16 105 views
0

我正在Mongodb不同的查詢,我有一個集合重複條目,我按照created_at做。但是我想取得沒有重複的價值。如何使用不同查詢在mongodb中查找重複值?

樣品JSON

{ 
    "posts": [{ 
     "id": "580a2eb915a0161010c2a562", 
     "name": "\"Ah Me Joy\" Porter", 
     "created_at": "15-10-2016" 
    }, { 
     "id": "580a2eb915a0161010c2a562", 
     "name": "\"Ah Me Joy\" Porter", 
     "created_at": "25-10-2016" 
    }, { 
     "id": "580a2eb915a0161010c2a562", 
     "name": "\"Ah Me Joy\" Porter", 
     "created_at": "01-10-2016" 
    }, { 
     "id": "580a2eb915a0161010c2bf572", 
     "name": "Hello All", 
     "created_at": "05-10-2016" 
    }] 
} 

MongoDB的查詢

db.getCollection('posts').find({"id" : ObjectId("580a2eb915a0161010c2a562")}) 

所以我想了解的MongoDB不同的查詢,請您通過我的帖子,讓我知道。

+0

你是什麼意思發現不同? – hyades

+0

@hyades所以當我做db.collection.find它不會獲取重複的值,它會忽略重複的值,並只顯示唯一的結果... –

+0

你收集有多個條目'id'。如果你想只有一個,你可以嘗試'findOne',它會選擇任意一個隨機的 – hyades

回答

0

嘗試如下:

db.getCollection('posts').distinct("id") 

這將返回所有的唯一ID集合posts在如下:

["580a2eb915a0161010c2a562", "580a2eb915a0161010c2bf572"] 

從MongoDB的文檔:

的例子使用inventory集合其中包含以下文件:

{ "_id": 1, "dept": "A", "item": { "sku": "111", "color": "red" }, "sizes": [ "S", "M" ] } 
{ "_id": 2, "dept": "A", "item": { "sku": "111", "color": "blue" }, "sizes": [ "M", "L" ] } 
{ "_id": 3, "dept": "B", "item": { "sku": "222", "color": "blue" }, "sizes": "S" } 
{ "_id": 4, "dept": "A", "item": { "sku": "333", "color": "black" }, "sizes": [ "S" ] } 

要返回非重複值的字段(dept):

db.inventory.distinct("dept") 

該方法返回以下不同部門的值的數組:

[ "A", "B" ] 

參考:

  1. https://docs.mongodb.com/v3.2/reference/method/db.collection.distinct/
0

按我的理解,你想這應該消除了收集

在重複id通過使用MongoDB中明顯不同的結果,這將返回不同的值列表

db.getCollection('posts').distinct("id"); 
["580a2eb915a0161010c2a562", "580a2eb915a0161010c2bf572"] 

所以你應該看看MongoDB的聚集

db.posts.aggregate(
{ "$group" : { "_id" : "$id", "name" : {"$first" : "$name"}, "created_at" : {"$first" : "$created_at"} }} 
) 
結果,消除重複 id文件

輸出將是列表