1

My current mongodb aggregate pipeline output is

[
    {
        "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----",        
    }
];

Actual response should be unique based on CustomerID

[
    {
        "CustomerID":"E001",
        "CustomerName":"Suresh",
        "CustomerPhone":"919889902----",        
    },
    {
        "CustomerID":"E002",
        "CustomerName":"Ramesh",
        "CustomerPhone":"919889902----",        
    },
    {
        "CustomerID":"E003",
        "CustomerName":"Kishore",
        "CustomerPhone":"919889902----",        
    }
];

I don't know what operator to use to get unique values from aggregate pipeline.

I am using $project, $sort for projection of response and $skip and $limit for pagination

Ratan Uday Kumar
  • 5,738
  • 6
  • 35
  • 54

1 Answers1

1

group by the value you want :

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

I assume that name and phone are the same for the same customer Id, otherwise replace $first with $addToSet in order to get all names and phones

Daphoque
  • 4,421
  • 1
  • 20
  • 31