How to retrieve only one document from a MongoDB collection
For a full overview of MongoDB and all my posts on it, check out my overview.
MongoDB has a convenient method called findOne
which is very similar to the find
method, except it, returns the actual document instead of a cursor and it will only return the first document. If you need to return multiple documents from a query, you'll have to stick to the find
or findMany
methods for now.
If we have the documents shown here in a collection called users
:
{
"name": "John Doe",
"email": "test@test.com",
"admin": false
},
{
"name": "Jane Doe",
"email": "test2@test2.com",
"admin": true
},
{
"name": "Bob Doe",
"email": "bob@bob.com",
"admin": true
}
If we run the following command in MongoDB:
db.users.findOne()
It will return the first document in the users
collection, since we're not specifying any filters.
{
"name": "John Doe",
"email": "test@test.com",
"admin": false
}
If we specify that we want only the admin
users:
db.users.findOne({admin: true})
Even though two users satisfy that filter, we will only get Jane Doe
since she is the first document that matches the filter.
{
"name": "Jane Doe",
"email": "test2@test2.com",
"admin": true
}
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