DEV Community

Donald Feury
Donald Feury

Posted on • Originally published at donaldfeury.xyz on

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
}
Enter fullscreen mode Exit fullscreen mode

If we run the following command in MongoDB:

db.users.findOne()
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

If we specify that we want only the admin users:

db.users.findOne({admin: true})
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)