DEV Community

Donald Feury
Donald Feury

Posted on • Originally published at donaldfeury.xyz on

1 1

How to retrieve specific documents from MongoDB using filters

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

While you can use the find method to read multiple documents out of MongoDB, it is more likely you only want a subset of that data. The find method can take two arguments and the first one determines what data is returned by the cursor. You'll often see or hear this first argument referred to as a "query" rather than a filter.

With the given data in a collection called users

{
    "name": "John Doe",
    "email": "test@test.com",
    "admin": false
},
{
    "name": "Jane Doe",
    "email": "test2@test2.com",
    "admin": false
}

Enter fullscreen mode Exit fullscreen mode

If I wanted to get only the user with the email "test@test.com", you can do this by passing in an object with some expressions that MongoDB will use to determine which data to return.

db.users.find({email: "test@test.com"})

Enter fullscreen mode Exit fullscreen mode

Will return:

{
    "name": "John Doe",
    "email": "test@test.com",
    "admin": false
}

Enter fullscreen mode Exit fullscreen mode

To get all the admin users:

db.users.find({admin: true})

Enter fullscreen mode Exit fullscreen mode

Will return nothing since we have no admin users in that dataset.

You can match on multiple fields as well:

db.users.find({admin: false, email: "test2@test2.com"})

Enter fullscreen mode Exit fullscreen mode

Will return:

{
    "name": "Jane Doe",
    "email": "test2@test2.com",
    "admin": false
}

Enter fullscreen mode Exit fullscreen mode

Reinvent your career. Join DEV.

It takes one minute and is worth it for your career.

Get started

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

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay