MongoDB Query Operators Tutorial

The MongoDB Query Operators are used to filter, manipulate, and retrieve data from your MongoDB collections.

Equality Operators

$eq: Matches values that are equal to a specified value.

db.products.find({ price: { $eq: 10 } });
       

$ne: Matches values that are not equal to a specified value.

db.products.find({ category: { $ne: "Electronics" } });
       

Comparison Operators

$gt: Matches values greater than a specified value.

db.products.find({ price: { $gt: 20 } });
       

$lt: Matches values less than a specified value.

db.products.find({ qty: { $lt: 100 } });
       

Logical Operators

$and: Joins query clauses with a logical AND.

db.products.find({ $and: [{ price: { $gt: 10 } }, { category: "Electronics" }] });
       

$or: Joins query clauses with a logical OR.

db.products.find({ $or: [{ category: "Electronics" }, { brand: "Samsung" }] });
       

Array Operators

$in: Matches any of the values in an array.

db.products.find({ tags: { $in: ["Tech", "Gadgets"] } });
       

$all: Matches arrays that contain all specified elements.

db.products.find({ categories: { $all: ["Electronics", "Appliances"] } });
       

Element Operators

$exists: Matches documents that contain a field.

db.customers.find({ email: { $exists: true } });
       

$type: Matches documents where the type of a field matches a specified type.

db.orders.find({ orderDate: { $type: "date" } });
       

Text Search Operators

$text: Performs full-text search on text fields.

db.articles.find({ $text: { $search: "mongodb tutorial" } });
       

Regular Expression Operators

$regex: Matches documents based on a regular expression pattern.

db.contacts.find({ name: { $regex: /^John/ } });
       

Array Element Operators

$elemMatch: Matches documents that contain an array element matching specified conditions.

db.posts.find({ comments: { $elemMatch: { author: "Alice", score: { $gt: 5 } } } });
       

Geospatial Operators

$near: Returns documents based on proximity to a specified point.

db.locations.find({ location: { $near: { $geometry: { type: "Point", coordinates: [12.34, 56.78] }, $maxDistance: 1000 } } });
       

Array Projection Operators

$slice: Limits the elements in an array field.

db.users.find({}, { interests: { $slice: 2 } });