Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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...

like image 625
Nikhil Avatar asked Nov 19 '16 09:11

Nikhil


People also ask

How can I get distinct values from a field in MongoDB?

To get distinct values, use distinct() in MongoDB. It finds the distinct values for a specified field across a single collection or view and returns the results in an array.

Can we use distinct in MongoDB?

To get unique values and ignore duplicates, use distinct() in MongoDB. The distinct() finds the distinct values for a specified field across a single collection and returns the results in an array.

Which command gives all the distinct values in MongoDB?

MongoDB – Distinct() Method In MongoDB, the distinct() method finds the distinct values for a given field across a single collection and returns the results in an array. It takes three parameters first one is the field for which to return distinct values and the others are optional.


1 Answers

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" ] }
like image 184
hyades Avatar answered Oct 02 '22 20:10

hyades