Hint: Use curly braces with key:value pairs for filters [OK]
Common Mistakes:
Using '=' or '==' inside filter object
Passing filter as a string
Missing curly braces around filter
3. Given the collection users with documents: {name: 'Bob', age: 30}, {name: 'Alice', age: 25}, {name: 'Bob', age: 22} What will db.users.findOne({name: 'Bob'}) return?
medium
A. {name: 'Bob', age: 22}
B. {name: 'Alice', age: 25}
C. {name: 'Bob', age: 30}
D. null
Solution
Step 1: Understand findOne returns first match
The findOne method returns the first document matching the filter in the collection's natural order.
Step 2: Identify the first matching document
Documents are stored in insertion order. The first document with name: 'Bob' is {name: 'Bob', age: 30}.
Final Answer:
{name: 'Bob', age: 30} -> Option C
Quick Check:
First matching document = {name: 'Bob', age: 30} [OK]
Hint: findOne returns the first matching document found [OK]
Common Mistakes:
Assuming findOne returns the last matching document
Expecting all matches instead of one
Confusing document order
4. What is wrong with this query? db.users.findOne(name: 'Alice')
medium
A. The filter key should be capitalized.
B. Missing curly braces around the filter object.
C. The collection name is incorrect.
D. Using findOne instead of find.
Solution
Step 1: Check filter syntax in findOne
The filter argument must be an object enclosed in curly braces, like {name: 'Alice'}.
Step 2: Identify the syntax error
The query misses curly braces around the filter, causing a syntax error.
Final Answer:
Missing curly braces around the filter object. -> Option B
Quick Check:
Filter must be an object = Missing curly braces around the filter object. [OK]
Hint: Always wrap filter in curly braces {} [OK]
Common Mistakes:
Omitting curly braces for filter
Confusing findOne with find
Assuming key names are case sensitive
5. You want to find a user document with email 'user@example.com' but only want to return the name and age fields. Which findOne query is correct?
hard
A. db.users.findOne({email: 'user@example.com'}, {name: 1, age: 1, email: 0})
B. db.users.findOne({email: 'user@example.com'}, {email: 1})
C. db.users.findOne({email: 'user@example.com'}, {name: 1, age: 1})
D. db.users.findOne({email: 'user@example.com'}, {name: 1, age: 1, _id: 0})
Solution
Step 1: Understand projection in findOne
The second argument to findOne is the projection object that specifies which fields to include (1) or exclude (0).
Step 2: Choose correct projection
To return only name and age and exclude _id, use {name: 1, age: 1, _id: 0}. db.users.findOne({email: 'user@example.com'}, {name: 1, age: 1, _id: 0}) matches this.