MongoDB MongoDB Query Language and Operators 1 — Questions and Answers
Question 1: Which MongoDB query operator matches documents where a field value is greater than a specified value?
- $gt (Correct answer)
- $gte
- $lt
- $lte
Correct answer: $gt
$gt (greater than) selects documents where the field value is strictly greater than the specified value.
Question 2: Which operator selects documents where a field value matches any value in a specified array?
- $exists
- $all
- $in (Correct answer)
- $elemMatch
Correct answer: $in
$in matches documents where the field value is equal to any value in the specified array.
Question 3: What does the $and operator do in a MongoDB query?
- Returns documents matching any one condition
- Returns documents where all conditions are true (Correct answer)
- Negates all conditions in the query
- Combines results from two collections
Correct answer: Returns documents where all conditions are true
$and performs a logical AND, returning only documents where all specified conditions are true.
Question 4: How do you apply a projection in a MongoDB find() query to return only specific fields?
- db.col.find({filter}, {field: true})
- db.col.find({filter}, {field: 1}) (Correct answer)
- db.col.find({field: 1})
- db.col.project({field: 1}).find({filter})
Correct answer: db.col.find({filter}, {field: 1})
Projections are passed as the second argument to find(), with fields set to 1 to include them.
Question 5: What does the $ne operator match in a MongoDB query?
- Documents where the field is null
- Documents where the field does not exist
- Documents where the field value is not equal to the specified value (Correct answer)
- Documents where the field is a non-empty string
Correct answer: Documents where the field value is not equal to the specified value
$ne (not equal) matches all documents where the field value does not equal the specified value.
Question 6: Which operator is used to match documents where an array field contains all of the specified elements?
- $in
- $all (Correct answer)
- $elemMatch
- $size
Correct answer: $all
$all matches arrays that contain every element in the specified list, regardless of order.
Question 7: What is the correct MongoDB syntax to sort query results in descending order by a field named 'score'?
- .sort({score: 0})
- .sort({score: 'desc'})
- .sort({score: false})
- .sort({score: -1}) (Correct answer)
Correct answer: .sort({score: -1})
In MongoDB, -1 specifies descending sort order and 1 specifies ascending sort order.
Which MongoDB query operator matches documents where a field value is greater than a specified value?