This content originally appeared on DEV Community and was authored by Donald Feury
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
}
This content originally appeared on DEV Community and was authored by Donald Feury
Donald Feury | Sciencx (2021-08-05T00:42:47+00:00) How to retrieve only one document from a MongoDB collection. Retrieved from https://www.scien.cx/2021/08/05/how-to-retrieve-only-one-document-from-a-mongodb-collection/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.