1 min read

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
}

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

Will return:

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

To get all the admin users:

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

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

Will return:

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

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