1

How to get the distinct values of all the fields within the mongodb collection using single query.

{ "_id": "1", "Gender": "male", "car": "bmw" , "house":"2bhk" , "married_to": "kalpu"},
{ "_id": "2", "Gender": "female", "car": nan , "house":"3bhk", "married_to": "kalpu"},
{ "_id": "3", "Gender": "female", "car": "audi", "house":"1bhk", "married_to": "deepa"},

This is an example with few fields, In my actual collection, each document has atleast 50 fields. So how to query effeciently that will return unique values within each of the fields? Thanks in advance for help.

Answer expected:

for each field,

  Gender:"male", "female"
  car   :"bmw", "audi",.....
  house : "3hbk","2bhk","1bhk"
  married_to: "kalpu","deepa",....
  ....
  ....
  ...
  

1 Answer 1

2

You can use aggregation pipeline $group stage with $addToSet operator

db.collection.aggregate([
  {
    $group: {
      _id: null,
      Gender: {
        "$addToSet": "$Gender"
      },
      car: {
        "$addToSet": "$car"
      },
      house: {
        "$addToSet": "$house"
      },
      married_to: {
        "$addToSet": "$married_to"
      },
      
    }
  }
]) 

Working Example

Sign up to request clarification or add additional context in comments.

3 Comments

hey, did this answer your question ?
Thanks, Yes it worked, But how to avoid "null" values being considered as distinct values.
null values are considered the same

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.