我当前的mongodb聚合管道输出是
[
{
"CustomerID":"E001",
"CustomerName":"Suresh",
"CustomerPhone":"919889902----",
},
{
"CustomerID":"E001",
"CustomerName":"Suresh",
"CustomerPhone":"919889902----",
},
{
"CustomerID":"E002",
"CustomerName":"Ramesh",
"CustomerPhone":"919889902----",
},
{
"CustomerID":"E003",
"CustomerName":"Kishore",
"CustomerPhone":"919889902----",
},
{
"CustomerID":"E002",
"CustomerName":"Ramesh",
"CustomerPhone":"919889902----",
},
{
"CustomerID":"E001",
"CustomerName":"Suresh",
"CustomerPhone":"919889902----",
}
];
根据 CustomerID
,实际响应应该是唯一的[
{
"CustomerID":"E001",
"CustomerName":"Suresh",
"CustomerPhone":"919889902----",
},
{
"CustomerID":"E002",
"CustomerName":"Ramesh",
"CustomerPhone":"919889902----",
},
{
"CustomerID":"E003",
"CustomerName":"Kishore",
"CustomerPhone":"919889902----",
}
];
我不知道使用什么运算符从聚合管道中获取唯一值。
我正在使用$ project,$ sort用于投射响应和$ skip和$ limit for pagination
答案 0 :(得分:1)
按您想要的值分组:
db.collection.aggregate([
{
$group:{
_id: "$CustomerID",
CustomerId: {$first:"$CustomerID"},
CustomerName: {$first: "$CustomerName"},
CustomerPhone: {$first: "$CustomerPhone"}
}
}
]);
我认为同一个客户ID的名称和电话是相同的,否则用$ addToSet替换$ first以获取所有名称和电话