Search code examples
mongodbcollectionsaggregatedistinctproject

MongoDB: How to not repeat a collection


My Query:

db.Customer.aggregate({$project:{"CustNum":1, "CustName":1, "_id":0}})

The Result:

{ "CustNum" : 101, "CustName" : "Juan Dela Cruz" }
{ "CustNum" : 103, "CustName" : "Jose Nicholas" }
{ "CustNum" : 101, "CustName" : "Juan Dela Cruz" }
{ "CustNum" : 101, "CustName" : "Juan Dela Cruz" }
{ "CustNum" : 101, "CustName" : "Maria Makiling" }

My Problem: As you can see I am supposed to have 3 names for CustName and CustNum. My output should look like this

{ "CustNum" : 101, "CustName" : "Juan Dela Cruz" }
{ "CustNum" : 103, "CustName" : "Jose Nicholas" }
{ "CustNum" : 101, "CustName" : "Maria Makiling" }

How to achieve this? I tried to use distinct but it only shows an error.

First attempt QUERY:

db.Customer.distinct().aggregate({$project:{"CustNum":1, "CustName":1, "_id":0}})

Second attempt QUERY:

 db.Customer.distinct().aggregate({$project:{"CustNum":1, "CustName":1, "_id":0}})

Solution

  • You need to use group,

    db.collection.aggregate([
      {
        "$group": {
          "_id": "$CustName",
          "CustName": {
            "$first": "$CustName"
          },
          "CustNum": {
            "$first": "$CustNum"
          },
          
        }
      }
    ])
    

    Working Mongo playground