我是环回新手,需要解决以下问题。我需要两个字段的mongo的不同结果(email和name)。
数据:
变量a=[{email:'x@gmail.com',name:'x'},{email:
'x@gmail.com',name:'x'},{email:'x@gmail.com',name:'z'}]
输出:
var a = [
{ email: 'x@gmail.com',name: 'x'},
{ email: 'x@gmail.com',name: 'z'}
]
如何在环回中使用以下聚合函数来获得所需的输出结果。
collection = db.tb;
result = collection.aggregate(
[
{"$group": { "_id": { email: "$email", name: "$name" } } }
]
);
(来源How to efficiently perform "distinct" with multiple keys?)
最佳答案
使用附加的$group
和$project
阶段投射所需的输出,Group
通过email
和name
,为每个唯一的
组合。
再次合并所有记录并累积group
使用_id
运算符在前一阶段获得。$push
字段并排除Project
字段。
代码:
result = collection.aggregate(
[
{$group:{"_id":{"email": "$email","name": "$name" }}},
{$group:{"_id":null,"records":{$push:"$_id"}}},
{$project:{"_id":0,"records":1}},
]
);
O/P:
{
"records" : [
{
"email" : "x@gmail.com",
"name" : "z"
},
{
"email" : "x@gmail.com",
"name" : "x"
}
]
}