Nikhil
Nikhil

Reputation: 467

performing distinct on multiple fields in mongodb

Let's say we have a collection of docs as follows :

[
  {
    "name" : "john",
    "age" : 23,
    "city": "New York",
    "gender": "M"
  },
  {
    "name" : "doe",
    "age" : 30,
    "city": "dubai",
    "gender": "M"
  },
  {
    "name" : "jean",
    "age" : 23,
    "city": "New York",
    "gender": "F"
  }
  {
    "name" : "phil",
    "age" : 24,
    "city": "Ohio",
    "gender": "M"
  }
]

Expected output :

{
  "name" : ["john","doe","jean","phil"],
  "age" : [23,30,24],
  "city": ["New York","Dubai","Ohio"],
  "gender": ["M","F"]
}

I tried using mongodb's distinct , but that will return me just uniques values for one particular field...I dont think we can pass multiple fields in distinct query...

Upvotes: 11

Views: 9330

Answers (1)

hyades
hyades

Reputation: 3170

The $addToSet is specifically for these kind of things.

db.coll.aggregate([
  {
    $group: 
    {
      _id: null,
      name: {$addToSet: '$name'},
      age: {$addToSet: '$age'},
      city: {$addToSet: '$city'},
      gender: {$addToSet: '$gender'}
    }
  }
])

which gives the output -

{ 
  "_id" : null, 
  "name" : [ "phil", "jean", "doe", "john" ], 
  "age" : [ 24, 30, 23 ], 
  "city" : [ "Ohio", "dubai", "New York" ], 
  "gender" : [ "F", "M" ] 
}

Upvotes: 15

Related Questions