Find Queries & Comparison Operators ($eq, $gt, $in, $nin)0%

Find Queries & Comparison Operators ($eq, $gt, $in, $nin)

Beginner12 min read•Updated: Jul 11, 2026
Study MaterialsCheatsheet

Find Queries & Comparison Operators ($eq, $gt, $in, $nin)

Querying data in MongoDB is accomplished using the find() and findOne() methods. Unlike SQL's SELECT * FROM table WHERE condition, MongoDB queries are expressed as JSON/BSON filter documents using specialized query operators.


1. Finding Documents: findOne() vs find()

JavaScript
// 1. findOne(): Returns the first matching document (or null)
const user = await db.collection('users').findOne({ email: 'priya@example.com' });
 
// 2. find(): Returns a CURSOR over all matching documents
const cursor = db.collection('courses').find({ isPublished: true });
const courses = await cursor.toArray(); // Convert cursor into JavaScript array

2. Comparison Operators Overview

OperatorMeaningExample
$eqEquals{ status: { $eq: 'ACTIVE' } } (or shorthand { status: 'ACTIVE' })
$neNot equals{ role: { $ne: 'banned' } }
$gtGreater than{ price: { $gt: 500 } }
$gteGreater than or equal to{ age: { $gte: 18 } }
$ltLess than{ inventory: { $lt: 10 } }
$lteLess than or equal to{ rating: { $lte: 4.5 } }
$inMatches any value in array{ category: { $in: ['Web', 'AI', 'Cloud'] } }
$ninMatches none of the values{ status: { $nin: ['ARCHIVED', 'DELETED'] } }

3. Practical Example: Querying Numeric Ranges and Inclusions

JavaScript
// Find premium courses priced between 1,000 and 5,000 in specific categories
const premiumCourses = await db.collection('courses').find({
category: { $in: ['Full-Stack', 'Data Science'] },
price: { $gte: 1000, $lte: 5000 },
isPublished: true
}).toArray();
 
console.log(`Found ${premiumCourses.length} matching courses.`);

Querying Nested Subdocuments:

Use dot notation enclosed in quotes to query fields inside embedded subdocuments:

JavaScript
// Query courses where instructor's experience is >= 5 years
const expertCourses = await db.collection('courses').find({
'instructor.experienceYears': { $gte: 5 }
}).toArray();

Interactive Quiz

Multiple Choice Questions

Question 1
What does collection.find() return in the MongoDB Node.js driver?
Question 2
Which comparison operator selects documents where a field matches any value specified in an array?
Question 3
How do you query a field named city located inside an embedded subdocument address in MongoDB?
Question 4
What filter matches all products whose rating is strictly greater than 4.5?
Question 5
What will collection.findOne({ email: 'nonexistent@test.com' }) return?

Next Lesson

Logical, Element & Array Query Operators ($and, $or, $exists, $all)

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

PrevNext