Bird
Raised Fist0
MongoDBquery~20 mins

Many-to-many with references in MongoDB - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Many-to-many Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ query_result
intermediate
2:00remaining
Find all books written by author with _id 'A1'

Given two collections authors and books with many-to-many references, which query returns all books written by the author with _id 'A1'?

MongoDB
db.books.find({ authors: 'A1' })
Adb.books.find({ author_id: 'A1' })
Bdb.authors.find({ books: 'A1' })
Cdb.books.find({ authors: 'A1' })
Ddb.books.find({ 'authors._id': 'A1' })
Attempts:
2 left
💡 Hint

Books store an array of author IDs in the authors field.

🧠 Conceptual
intermediate
1:30remaining
Why use references for many-to-many relationships in MongoDB?

What is the main reason to use references instead of embedding documents for many-to-many relationships in MongoDB?

ATo avoid data duplication and keep data consistent across collections
BBecause MongoDB does not support embedding arrays
CTo improve query speed by storing all data in one document
DBecause references automatically enforce foreign key constraints
Attempts:
2 left
💡 Hint

Think about data duplication and consistency when the same data appears in multiple places.

📝 Syntax
advanced
2:30remaining
Correct aggregation to lookup authors for each book

Which aggregation pipeline correctly joins books with authors to get author details for each book?

MongoDB
db.books.aggregate([
  { $lookup: {
      from: 'authors',
      localField: 'authors',
      foreignField: '_id',
      as: 'authorDetails'
  }}
])
Adb.books.aggregate([{ $lookup: { from: 'authors', localField: 'authorIds', foreignField: '_id', as: 'authorDetails' }}])
Bdb.books.aggregate([{ $lookup: { from: 'authors', localField: '_id', foreignField: 'authors', as: 'authorDetails' }}])
Cdb.books.aggregate([{ $lookup: { from: 'authors', localField: 'authors', foreignField: 'id', as: 'authorDetails' }}])
Ddb.books.aggregate([{ $lookup: { from: 'authors', localField: 'authors', foreignField: '_id', as: 'authorDetails' }}])
Attempts:
2 left
💡 Hint

Match localField with the array field in books and foreignField with the key in authors.

🔧 Debug
advanced
2:00remaining
Why does this query return no results?

Given books documents with authors as an array of ObjectIds, why does this query return no results?

db.books.find({ authors: '507f1f77bcf86cd799439011' })
ABecause the <code>authors</code> field is an embedded document, not an array
BBecause the query compares string to ObjectId, types must match
CBecause the query should use <code>$in</code> operator
DBecause the <code>authors</code> field is missing in all documents
Attempts:
2 left
💡 Hint

Check the data type of the authors array elements and the query value.

❓ optimization
expert
3:00remaining
Best index to optimize many-to-many author-book queries

To optimize queries that find all books by a given author ID stored in the authors array field, which index is best?

ACreate a multikey index on the <code>authors</code> field in the <code>books</code> collection
BCreate a unique index on the <code>_id</code> field in the <code>authors</code> collection
CCreate a compound index on <code>authors</code> and <code>title</code> fields in <code>books</code>
DCreate a text index on the <code>authors</code> field in <code>books</code>
Attempts:
2 left
💡 Hint

Think about indexing array fields for efficient membership queries.

Practice

(1/5)
1. What does a many-to-many relationship with references mean in MongoDB?
easy
A. Only one collection has references, the other does not.
B. One collection stores all data, the other is empty.
C. Both collections store arrays of IDs pointing to each other.
D. Data is duplicated in both collections without IDs.

Solution

  1. Step 1: Understand many-to-many references

    In MongoDB, many-to-many means each document in one collection can link to many documents in another, and vice versa.
  2. Step 2: Identify how references are stored

    This is done by storing arrays of IDs in both collections, so each side knows its related documents.
  3. Final Answer:

    Both collections store arrays of IDs pointing to each other. -> Option C
  4. Quick Check:

    Many-to-many references = arrays of IDs in both collections [OK]
Hint: Many-to-many means both sides hold arrays of IDs [OK]
Common Mistakes:
  • Thinking only one side stores references
  • Confusing many-to-many with embedding all data
  • Assuming data is duplicated without IDs
2. Which of the following is the correct way to store references for a many-to-many relationship between students and courses collections in MongoDB?
easy
A. { _id: 1, name: 'Alice', courses: 101 } and { _id: 101, title: 'Math', students: 1 }
B. { _id: 1, name: 'Alice', courses: [101, 102] } and { _id: 101, title: 'Math', students: [1, 2] }
C. { _id: 1, name: 'Alice', courses: 'Math' } and { _id: 101, title: 'Math', students: 'Alice' }
D. { _id: 1, name: 'Alice', courses: [] } and { _id: 101, title: 'Math', students: [] }

Solution

  1. Step 1: Check reference format

    References must be arrays of IDs to represent many-to-many links.
  2. Step 2: Validate { _id: 1, name: 'Alice', courses: [101, 102] } and { _id: 101, title: 'Math', students: [1, 2] }

    { _id: 1, name: 'Alice', courses: [101, 102] } and { _id: 101, title: 'Math', students: [1, 2] } shows arrays of IDs in both collections, correctly linking students and courses.
  3. Final Answer:

    { _id: 1, name: 'Alice', courses: [101, 102] } and { _id: 101, title: 'Math', students: [1, 2] } -> Option B
  4. Quick Check:

    Arrays of IDs in both collections = correct syntax [OK]
Hint: Use arrays of IDs, not single values or names [OK]
Common Mistakes:
  • Using single ID instead of array for many-to-many
  • Storing names instead of IDs as references
  • Leaving reference arrays empty without reason
3. Given these two documents:
{ _id: 1, name: 'Bob', courses: [201, 202] }
{ _id: 201, title: 'History', students: [1, 3] }
What will be the result of querying the courses array for student with _id: 1?
medium
A. ['History']
B. [1, 3]
C. []
D. [201, 202]

Solution

  1. Step 1: Identify the student's courses field

    The student document with _id 1 has a courses array: [201, 202].
  2. Step 2: Understand the query result

    Querying the courses array for this student returns the IDs [201, 202], not titles or student IDs.
  3. Final Answer:

    [201, 202] -> Option D
  4. Quick Check:

    Student's courses array = [201, 202] [OK]
Hint: Query returns stored IDs, not linked document fields [OK]
Common Mistakes:
  • Confusing course IDs with student IDs
  • Expecting course titles instead of IDs
  • Assuming empty array if unsure
4. You have these two collections:
students: { _id: 2, name: 'Eve', courses: [301] }
courses: { _id: 301, title: 'Science', students: [] }
What is the problem with this many-to-many reference setup?
medium
A. The students array in courses is missing the student ID.
B. The courses array in students is empty.
C. The student document is missing the courses field.
D. The course document has an invalid _id.

Solution

  1. Step 1: Check references in both collections

    The student document lists course 301, but the course document's students array is empty.
  2. Step 2: Identify missing reciprocal reference

    For many-to-many, both sides must reference each other. The course's students array should include student ID 2.
  3. Final Answer:

    The students array in courses is missing the student ID. -> Option A
  4. Quick Check:

    Both sides must reference each other [OK]
Hint: Both sides must list each other's IDs [OK]
Common Mistakes:
  • Ignoring missing reciprocal references
  • Assuming one side is enough
  • Confusing empty arrays with missing fields
5. You want to find all courses taken by students who are enrolled in both course 401 and 402. Given collections with many-to-many references, which MongoDB aggregation pipeline stage helps find students enrolled in both courses?
hard
A. { $match: { courses: { $all: [401, 402] } } }
B. { $match: { courses: { $in: [401, 402] } } }
C. { $match: { courses: 401 } }
D. { $match: { courses: { $size: 2 } } }

Solution

  1. Step 1: Understand the query goal

    We want students enrolled in both courses 401 and 402, so their courses array must contain both IDs.
  2. Step 2: Choose correct MongoDB operator

    The $all operator matches arrays containing all specified elements, perfect for this case.
  3. Final Answer:

    { $match: { courses: { $all: [401, 402] } } } -> Option A
  4. Quick Check:

    $all matches arrays containing all elements [OK]
Hint: Use $all to match arrays containing all specified IDs [OK]
Common Mistakes:
  • Using $in matches any, not all elements
  • Using $size only checks array length, not content
  • Matching single course ID misses the second course
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard