Given two collections authors and books with many-to-many references, which query returns all books written by the author with _id 'A1'?
db.books.find({ authors: 'A1' })Books store an array of author IDs in the authors field.
The books collection has an authors array with author IDs. Querying { authors: 'A1' } finds books where 'A1' is in that array.
What is the main reason to use references instead of embedding documents for many-to-many relationships in MongoDB?
Think about data duplication and consistency when the same data appears in multiple places.
Using references avoids duplicating data in multiple documents, which helps keep data consistent and easier to update.
Which aggregation pipeline correctly joins books with authors to get author details for each book?
db.books.aggregate([
{ $lookup: {
from: 'authors',
localField: 'authors',
foreignField: '_id',
as: 'authorDetails'
}}
])Match localField with the array field in books and foreignField with the key in authors.
The authors field in books contains author IDs. The _id field in authors matches those IDs. Option D correctly sets these fields.
Given books documents with authors as an array of ObjectIds, why does this query return no results?
db.books.find({ authors: '507f1f77bcf86cd799439011' })Check the data type of the authors array elements and the query value.
The authors array contains ObjectId values, but the query uses a string. MongoDB requires matching types for equality.
To optimize queries that find all books by a given author ID stored in the authors array field, which index is best?
Think about indexing array fields for efficient membership queries.
A multikey index on the authors array allows MongoDB to efficiently find documents where the array contains a specific author ID.