OneCompiler

How can I retrieve all the unique values of a field in Mongodb?

I have started working on Mongodb recently. I have a collection similar to the below one and i want to know the unique values of the field genre.

{"_id":1,"title":"The Avengers","genre":"Action"}
{"_id":2,"title":"Mr Bean","genre":"Comedy"}
{"_id":3,"title":"Heroic Bloodshed","genre":"Action"}
{"_id":4,"title":"The Lion King","genre":"Kids"}
{"_id":5,"title":"James Bond","genre":"Action"}
{"_id":6,"title":"Harry Potter","genre":"Fantasy"}
{"_id":7,"title":"Twilight","genre":"Fantasy"}
{"_id":8,"title":"Toy Story","genre":"Kids"}

1 Answer

5 years ago by

You can get all the unique values of a field by using the below command

db.collectionName.distinct("genre")
5 years ago by Jahaan