Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB Compass: select distinct field values

I am using MongoDB Compass and don't have Mongo Shell. I need to build a query using MongoDB Compass tool to select distinct values of the "genre" field from my collection.

compass tool screenshot

Sample Input:

{"_id":{"$oid":"58c59c6a99d4ee0af9e0c34e"},"title":"Bateau-mouche sur la Seine","year":{"$numberInt":"1896"},"imdbId":"tt0000042","genre":["Documentary”,”Short”],"viewerRating":{"$numberDouble":"3.8"},"viewerVotes":{"$numberInt":"17"},"director":"Georges Mlis"}
{"_id":{"$oid":"58c59c6a99d4ee0af9e0c340"},"title":"Watering the Flowers","year":{"$numberInt":"1896"},"imdbId":"tt0000035","genre":["Short”],"viewerRating":{"$numberDouble":"5.3"},"viewerVotes":{"$numberInt":"33"},"director":"Georges M�li�s"}
{"_id":{"$oid":"58c59c6a99d4ee0af9e0c34a"},"title":"The Boxing Kangaroo","year":{"$numberInt":"1896"},"imdbId":"tt0000048","genre":["Short”],"viewerRating":{"$numberDouble":"5.2"},"viewerVotes":{"$numberInt":"48"},"director":"Birt Acres"}

Expected output: Documentary, Short

like image 280
javapedia.net Avatar asked Nov 01 '19 02:11

javapedia.net


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.

How do I run a distinct query in MongoDB compass?

You can do this via aggregation framework in Compass, using $unwind and $group. The $unwind is performed to create a unique document for each element in the target array, which enables the $addToSet operator in the $group stage to then capture the genres as distinct elements.

Can we use find and distinct together in MongoDB?

Both the find and distinct operations are very useful when it comes to retrieving data from MongoDB. The find operation returns the data all at once or according to the query and projection. The distinct operation has a special functionality of retrieving unique values of a specified field.


Video Answer


1 Answers

You can do this via aggregation framework in Compass, using $unwind and $group. The $unwind is performed to create a unique document for each element in the target array, which enables the $addToSet operator in the $group stage to then capture the genres as distinct elements.

Pipeline:

[
  {
    $unwind: {
      path: '$genre',
      preserveNullAndEmptyArrays: true
    }
  },
  {
    $group: {
      _id: null,
      uniqueGenres: { $addToSet: '$genre' }
    }
  }
]

See screenshot below for Compass example:

enter image description here

like image 164
christian Avatar answered Nov 15 '22 17:11

christian