Search code examples
mongodbmongodb-compass

Is there a way to get all distinct values for a field in Mongo Compass?


I would like to be able to get all the distinct values for a field or nested field in MongoDB Compass.


Solution

  • Here's a way that I've been using in Compass.

    If you go into Compass to the collection you want and go to the aggregation tab, you can unwind and group as such:

    Select $unwind and then fill in the field you want, prefixed with $. I usually ignore null and empty arrays if the field is an array.

    {
      path: '$displayFirstName',
      preserveNullAndEmptyArrays: false
    }
    

    Then use a $group stage to group the values and add them to a set:

    {
      _id: null,
      uniqueFirstNames: {
        $addToSet: '$displayFirstName'
      }
    }
    

    The unique list of values will be displayed on the right of the $group stage.

    If the value is nested and you want to flatten the results, just add more $unwind stages per level before the final $group stage. For example, if you had user.addresses which is an array of objects and you wanted to get all the possible address types of all your users as a flattened list you could do this.

    $unwind

    {
      path: '$addresses',
      preserveNullAndEmptyArrays: false
    }
    

    2nd $unwind

    {
      path: '$addresses.type',
      preserveNullAndEmptyArrays: false
    }
    

    $group

    {
      _id: null,
      uniqueAddressTypes: {
        $addToSet: '$addresses.type'
      }
    }