How to find all the distinct values of a field across your documents in MongoDB using the distinct aggregation method

For a full overview of MongoDB and all my posts on it, check out my overview.

If you want to find out all the different values for a field across all the documents in a collection, you can use the ready-made distinct aggregation method to find that out.

With the given data in a collection called podcasts:

{
	{
		"name": "Tech Over Tea",
		"episodeName": "#75 Welcome Our Hacker Neko Waifu | Cyan Nyan",
		"dateAired": ISODate("2021-08-02"),
		"listenedTo": true,
	},
	{
		"name": "Tech Over Tea",
		"episodeName": "Neckbeards Anonymous - Tech Over Tea #20 - feat Donald Feury",
		"dateAired": ISODate("2020-07-13"),
		"listenedTo": true
	},
	{
		"name": "Tech Over Tea",
		"episodeName": "#34 The Return Of The Clones - feat Bryan Jenks",
		"dateAired": ISODate("2020-10-19"),
		"listenedTo": false
	}
}

If you run the following command:

db.podcasts.distinct("episodeName")

The result will be:

[
	"#75 Welcome Our Hacker Neko Waifu | Cyan Nyan",
	"Neckbeards Anonymous - Tech Over Tea #20 - feat Donald Feury",
	"#34 The Return Of The Clones - feat Bryan Jenks"
]

Notice that the result is all the different values for the field episodeName.

You can also do the same on a query result:

db.podcasts.distinct("dateAired", {listenedTo: true})

Will return:

[ISODate("2021-08-02"),ISODate("2020-07-13")]

Did you find this information useful? If so, consider heading over to my donation page and drop me some support.

Want to ask a question or just chat? Contact me here