0
0
MongoDBquery~30 mins

$nin for not in set in MongoDB - Mini Project: Build & Apply

Choose your learning style9 modes available
$nin for not in set in MongoDB
📖 Scenario: You are managing a small online bookstore database. You want to find books that are not in certain genres to recommend to customers who want something different.
🎯 Goal: Build a MongoDB query using the $nin operator to find books whose genre is not in a given list of genres.
📋 What You'll Learn
Create a collection called books with specific book documents
Define a list of genres to exclude
Write a query using $nin to find books not in those genres
Complete the query to return only the book titles
💡 Why This Matters
🌍 Real World
Filtering data to exclude certain categories is common in recommendation systems, reporting, and data analysis.
💼 Career
Understanding $nin helps in writing flexible MongoDB queries for real-world applications like filtering products, users, or content.
Progress0 / 4 steps
1
Create the books collection with sample data
Create a MongoDB collection called books and insert these exact documents: { title: "The Hobbit", genre: "Fantasy" }, { title: "1984", genre: "Dystopian" }, { title: "To Kill a Mockingbird", genre: "Classic" }, { title: "The Great Gatsby", genre: "Classic" }, { title: "Neuromancer", genre: "Science Fiction" }.
MongoDB
Need a hint?

Use db.books.insertMany([...]) with the exact documents listed.

2
Define the list of genres to exclude
Create a variable called excludedGenres and set it to an array containing the strings "Classic" and "Dystopian".
MongoDB
Need a hint?

Use const excludedGenres = ["Classic", "Dystopian"] to define the array.

3
Write the query using $nin to find books not in excluded genres
Write a MongoDB query called query that finds documents in books where the genre field is $nin the excludedGenres array.
MongoDB
Need a hint?

Use { genre: { $nin: excludedGenres } } to build the query object.

4
Complete the query to return only book titles
Write a MongoDB find command using query to find matching books in books and project only the title field (exclude _id). Save this to a variable called result.
MongoDB
Need a hint?

Use db.books.find(query, { title: 1, _id: 0 }) to get only titles.