DEV Community

Donald Feury
Donald Feury

Posted on • Originally published at donaldfeury.xyz on

1 1

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 overiew.

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
    }
}

Enter fullscreen mode Exit fullscreen mode

If you run the following command:

db.podcasts.distinct("episodeName")

Enter fullscreen mode Exit fullscreen mode

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"
]

Enter fullscreen mode Exit fullscreen mode

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})

Enter fullscreen mode Exit fullscreen mode

Will return:

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

Enter fullscreen mode Exit fullscreen mode

Do your career a big favor. Join DEV. (The website you're on right now)

It takes one minute, it's free, and is worth it for your career.

Get started

Community matters

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay