0
0
MongoDBquery~30 mins

Multikey indexes for arrays in MongoDB - Mini Project: Build & Apply

Choose your learning style9 modes available
Create and Query Multikey Indexes for Arrays in MongoDB
📖 Scenario: You are managing a MongoDB collection that stores information about books in a library. Each book document contains a title and an array of authors. You want to create an index on the authors array to speed up searches for books by author.
🎯 Goal: Build a MongoDB collection with book documents containing an array of authors. Create a multikey index on the authors field. Then write a query to find all books by a specific author.
📋 What You'll Learn
Create a collection called books with documents having title and authors fields
Insert three book documents with exact titles and authors arrays
Create a multikey index on the authors field
Write a query to find all books where authors array contains 'Jane Austen'
💡 Why This Matters
🌍 Real World
Libraries, bookstores, and content platforms often store multiple authors per book. Multikey indexes help quickly find books by any author.
💼 Career
Database developers and administrators use multikey indexes to optimize queries on array fields in MongoDB, improving application performance.
Progress0 / 4 steps
1
Create the books collection with three book documents
Insert three documents into the books collection with these exact fields and values: { title: 'Pride and Prejudice', authors: ['Jane Austen'] }, { title: 'Good Omens', authors: ['Neil Gaiman', 'Terry Pratchett'] }, and { title: 'The Hobbit', authors: ['J.R.R. Tolkien'] }.
MongoDB
Need a hint?

Use db.books.insertMany() with an array of three objects, each having title and authors fields.

2
Create a multikey index on the authors field
Create an index on the authors field of the books collection using db.books.createIndex().
MongoDB
Need a hint?

Use db.books.createIndex({ authors: 1 }) to create the multikey index.

3
Write a query to find books by 'Jane Austen'
Write a query using db.books.find() to find all documents where the authors array contains the string 'Jane Austen'.
MongoDB
Need a hint?

Use db.books.find({ authors: 'Jane Austen' }) to find matching documents.

4
Add a projection to show only the title field in the query result
Modify the previous db.books.find() query to include a projection that returns only the title field and excludes the _id field.
MongoDB
Need a hint?

Add a second argument to db.books.find() with { title: 1, _id: 0 } to project only the title.