0
0
MongoDBquery~30 mins

Insert with arrays in MongoDB - Mini Project: Build & Apply

Choose your learning style9 modes available
Insert Documents with Arrays in MongoDB
📖 Scenario: You are managing a small library database. Each book can have multiple authors. You want to store books with their authors as an array inside each document.
🎯 Goal: Create a MongoDB collection called books and insert documents where each book has a title and an array of authors.
📋 What You'll Learn
Create a books collection with at least two documents
Each document must have a title field with a string value
Each document must have an authors field which is an array of strings
Use the insertMany() method to add the documents
💡 Why This Matters
🌍 Real World
Storing books with multiple authors is common in library databases, publishing systems, and online bookstores.
💼 Career
Knowing how to insert documents with arrays is essential for working with MongoDB in real-world applications like content management and cataloging.
Progress0 / 4 steps
1
Create the books collection with two book documents
Create a variable called books and assign it an array with two objects. The first object should have title set to "The Great Gatsby" and authors set to an array with "F. Scott Fitzgerald". The second object should have title set to "Good Omens" and authors set to an array with "Neil Gaiman" and "Terry Pratchett".
MongoDB
Need a hint?

Remember to use square brackets [] for arrays and curly braces {} for objects.

2
Prepare the books collection for insertion
Create a variable called collection and assign it the MongoDB collection named books using db.collection('books').
MongoDB
Need a hint?

Use db.collection('books') to get the collection object.

3
Insert the books array into the collection
Use the insertMany() method on collection to insert the books array.
MongoDB
Need a hint?

Call insertMany() on the collection and pass the books array.

4
Confirm the insertion by querying all documents
Create a variable called allBooks and assign it the result of collection.find().toArray() to get all documents from the books collection.
MongoDB
Need a hint?

Use find() with no arguments to get all documents, then convert to array with toArray().