2016-11-16 104 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文件

输出将是列表