Search code examples
jsonmongodbfieldmongodb-compassunique-values

MongoDB Compass: How to select Distinct Values of a Field


I have a MongoDB database where each entry has a 'comment' field. I'm using MongoDB Compass to connect to it, and trying to find all unique values of the 'comment' field. I tried the following code in the 'Aggregations' Tab of Compass (see image below), but I didn't get any result:

{$group: {
  _id: null,
  unique_comments: {
    $addToSet: comment
  }
}

An example of the data, in JSON format, is:

{"name":"Hannah Maxwell","date":"2020-01-07T20:16:13.931629-08:00","comment":"Maybe I like camping","location":{"latitude":43.81710433959961,"longitude":-79.42430114746094,"country":"CA","region":"ON"},"likes":1,"responses":24}
{"name":"Jordan Rodriguez","date":"2019-04-28T20:16:13.931629-07:00","comment":"I hate skiing","location":{"latitude":43.41518783569336,"longitude":-80.51475524902344,"country":"CA","region":"ON"},"likes":5,"responses":1}
{"name":"Bodhi Mckenzie","date":"2019-07-09T20:16:13.931629-07:00","comment":"I think I might like skiing","location":{"latitude":43.65549087524414,"longitude":-79.38555908203125,"country":"CA","region":"ON"},"likes":65,"responses":5}

Image of MongoDB compass Aggregation Tab


Solution

  • In MongoDB Compass you need to pick the Aggregation Pipeline stage from the menu, try:

    enter image description here

    The preview data should get displayed on the right-hand side