如何使用distinct查询在mongodb中查找重复值?

时间:2016-11-16 07:07:12

标签: node.js mongodb distinct-values

我正在开发Mongodb独特查询,我有一个重复输入的集合,我按照created_at进行操作。但我想在没有重复值的情况下获取。

示例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的独特查询,请通过我的帖子告诉我。

2 个答案:

答案 0 :(得分:0)

尝试如下:

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

它将返回集合posts中的所有唯一ID,如下所示:

["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" )

该方法返回以下不同dept值的数组:

[ "A", "B" ]

参考:

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

答案 1 :(得分:0)

根据我的理解,您希望得到截然不同的结果,这样可以消除该集合中的重复id

通过在mongodb中使用distinct,它将返回不同值的列表

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

所以你应该研究mongodb聚合

db.posts.aggregate(
{ "$group" : { "_id" : "$id", "name" : {"$first" : "$name"}, "created_at" : {"$first" : "$created_at"} }}
)

输出结果列表将消除重复的id文档