0
0
MongoDBquery~30 mins

findOne method in MongoDB - Mini Project: Build & Apply

Choose your learning style9 modes available
Using the MongoDB findOne Method
📖 Scenario: You are managing a small library database. You want to find details about a specific book by its title.
🎯 Goal: Build a MongoDB query using the findOne method to retrieve a single book document by its title.
📋 What You'll Learn
Create a collection named books with specific book documents
Define a query filter to find a book by its exact title
Use the findOne method with the filter
Return the found book document
💡 Why This Matters
🌍 Real World
Finding a single record in a database is common in apps like libraries, stores, or user profiles.
💼 Career
Knowing how to use findOne helps you retrieve specific data efficiently in backend development and database management.
Progress0 / 4 steps
1
Create the books collection with sample data
Create a variable called books that represents a MongoDB collection. Insert these exact documents into books: { title: 'The Hobbit', author: 'J.R.R. Tolkien', year: 1937 }, { title: '1984', author: 'George Orwell', year: 1949 }, and { title: 'To Kill a Mockingbird', author: 'Harper Lee', year: 1960 }.
MongoDB
Need a hint?

Use db.collection('books') to get the collection. Use insertMany to add multiple documents.

2
Define a filter to find a book by title
Create a variable called filter and set it to an object that finds the book with the title exactly equal to '1984'.
MongoDB
Need a hint?

The filter is an object with the key title and value '1984'.

3
Use findOne to get the book document
Create a variable called book and assign it the result of calling books.findOne(filter).
MongoDB
Need a hint?

Use await books.findOne(filter) to get the single matching document.

4
Complete the query by exporting the found book
Add a line to export the variable book using module.exports = book;.
MongoDB
Need a hint?

Use module.exports = book; to export the result.