21
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": "[email protected]",
"admin": false
},
{
"name": "Jane Doe",
"email": "[email protected]",
"admin": false
}
If I wanted to get only the user with the email "[email protected]", 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: "[email protected]"})
Will return:
{
"name": "John Doe",
"email": "[email protected]",
"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: "[email protected]"})
Will return:
{
"name": "Jane Doe",
"email": "[email protected]",
"admin": false
}
21