DEV Community

Donald Feury
Donald Feury

Posted on • Originally published at donaldfeury.xyz on

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

Top comments (0)