鉴于此数据集:
#![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}
])
答案 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 }
}
])