如何找到没有给定字段的重复值的mongo文档

时间:2015-05-28 12:14:20

标签: mongodb

鉴于此数据集:

#![feature(collections)]

我需要一种方法来列出所有没有重复值的文档,比如说字段“a”。

所以它需要返回:

db.mycollection.insert([
  {a:1, b:2, c:3},
  {a:1, b:3, c:4},
  {a:0, b:1, c:3},
  {a:3, b:2, c:4}
])

2 个答案:

答案 0 :(得分:1)

您需要使用 aggregation framework 来获得所需的结果。聚合管道如下所示:

db.mycollection.aggregate([
   {
       "$group": {
           "_id": "a",
           "data": { "$first": "$$ROOT" },
           "count": { "$sum": 1 }
       }
   },
   {
       "$match": { "count": 1 }
   },
   {
       "$project": {
           "_id": 0, "a": "$data.a", "b": "$data.b", "c": "$data.c" 
       }
   }
])

答案 1 :(得分:1)

在上面扩展我的评论,首先按a对结果进行分组并添加count,然后使用count过滤条目1:

db.mycollection.aggregate([
  {
    $group : { _id : "$a", "count" : { $sum : 1 }, entries : { $push: "$$ROOT" } }
  },
  {
    "$match" : { "count" : 1 }
  }
])