如何从mongodb聚合管道中获取唯一值

时间:2017-12-07 11:32:27

标签: node.js mongodb mongoose

我当前的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

1 个答案:

答案 0 :(得分:1)

按您想要的值分组:

db.collection.aggregate([
   {
     $group:{
       _id: "$CustomerID",
       CustomerId: {$first:"$CustomerID"},
       CustomerName: {$first: "$CustomerName"},
       CustomerPhone: {$first: "$CustomerPhone"}
    }
  }
]);

我认为同一个客户ID的名称和电话是相同的,否则用$ addToSet替换$ first以获取所有名称和电话