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...
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.
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.
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.
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" ] }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With