Write, Run & Share MongoDB queries online using OneCompiler's MongoDB online editor for free. It's one of the robust, feature-rich online editors for MongoDB. Getting started with the OneCompiler's MongoDB editor is really simple and pretty fast. The editor shows sample boilerplate code when you choose language as 'MongoDB' and start writing queries to learn and test online without worrying about tedious process of installation.
MongoDB is a document-oriented NoSQL database designed for scalability and flexibility. Instead of storing data in tables with rows, MongoDB stores documents in JSON-like format (BSON) within collections. This schema-flexible approach allows documents in the same collection to have different fields, making it ideal for agile development, unstructured data, and applications with evolving requirements.
MongoDB provides three methods to insert documents: insertOne() for single documents, insertMany() for arrays of documents, and the legacy insert() for both. Documents are JSON-like objects with field-value pairs. MongoDB automatically creates the collection if it doesn't exist and generates a unique _id field if not provided.
// Insert single document
db.employees.insertOne({
empId: 1,
name: "Clark",
dept: "Sales",
salary: 50000,
})
// Insert multiple documents
db.employees.insertMany([
{ empId: 2, name: "Dave", dept: "Accounting", salary: 45000 },
{ empId: 3, name: "Ava", dept: "Sales", salary: 55000 },
{ empId: 4, name: "Bob", dept: "Engineering", salary: 65000 },
])
// Insert with nested document
db.employees.insertOne({
empId: 5,
name: "Eve",
dept: "HR",
salary: 52000,
contact: {
email: "[email protected]",
phone: "555-0100",
},
skills: ["communication", "recruiting", "training"],
})
The find() method queries documents from a collection. Pass a filter object to match specific documents, or an empty object {} to retrieve all. Use projection as the second parameter to include or exclude fields. find() returns a cursor; use toArray() for all results or iterate with forEach(). findOne() returns a single matching document.
// Find all documents
db.employees.find({})
// Find with filter
db.employees.find({ dept: "Sales" })
// Find single document
db.employees.findOne({ empId: 1 })
// Find with multiple conditions (AND)
db.employees.find({
dept: "Sales",
salary: { $gte: 50000 },
})
// Find with OR condition
db.employees.find({
$or: [{ dept: "Sales" }, { dept: "Engineering" }],
})
// Find with projection (include/exclude fields)
db.employees.find({ dept: "Sales" }, { name: 1, salary: 1, _id: 0 })
MongoDB provides comparison operators for filtering: $eq (equal), $ne (not equal), $gt (greater than), $gte (greater or equal), $lt (less than), $lte (less or equal), $in (in array), and $nin (not in array). These operators enable precise queries for numeric, string, and date comparisons within filter conditions.
// Greater than
db.employees.find({ salary: { $gt: 50000 } })
// Less than or equal
db.employees.find({ salary: { $lte: 55000 } })
// Not equal
db.employees.find({ dept: { $ne: "Sales" } })
// In array of values
db.employees.find({
dept: { $in: ["Sales", "Engineering"] },
})
// Range query (between)
db.employees.find({
salary: { $gte: 45000, $lte: 60000 },
})
// Not in array
db.employees.find({
dept: { $nin: ["HR", "Accounting"] },
})
Logical operators combine multiple conditions: $and requires all conditions to match, $or requires at least one, $not inverts a condition, and $nor matches when all conditions fail. While implicit AND works by listing multiple fields, explicit $and is needed when applying multiple conditions to the same field.
// Explicit AND (needed for same field)
db.employees.find({
$and: [{ salary: { $gte: 45000 } }, { salary: { $lte: 60000 } }],
})
// OR with complex conditions
db.employees.find({
$or: [{ dept: "Sales", salary: { $gte: 50000 } }, { dept: "Engineering" }],
})
// NOR (none match)
db.employees.find({
$nor: [{ dept: "Sales" }, { salary: { $lt: 45000 } }],
})
MongoDB provides updateOne() for single documents, updateMany() for multiple matches, and replaceOne() to replace entire documents. Use update operators like $set (set fields), $unset (remove fields), $inc (increment), and $push (add to arrays). Always use operators with updateOne/updateMany to modify specific fields.
// Update single document
db.employees.updateOne({ empId: 1 }, { $set: { salary: 55000 } })
// Update multiple fields
db.employees.updateOne(
{ empId: 2 },
{
$set: { dept: "Marketing", salary: 52000 },
$currentDate: { lastModified: true },
}
)
// Update multiple documents
db.employees.updateMany({ dept: "Sales" }, { $inc: { salary: 5000 } })
// Add field to document
db.employees.updateOne({ empId: 1 }, { $set: { bonus: 10000 } })
// Remove field from document
db.employees.updateOne({ empId: 1 }, { $unset: { bonus: "" } })
// Upsert (insert if not exists)
db.employees.updateOne(
{ empId: 10 },
{ $set: { name: "New Employee", dept: "Sales" } },
{ upsert: true }
)
MongoDB excels at array handling with operators for querying and modifying arrays. Use $push to add elements, $pull to remove, $addToSet for unique additions, and $pop to remove first/last. Query arrays with $elemMatch for complex conditions, $all for matching all elements, and $size for array length matching.
// Add to array
db.employees.updateOne({ empId: 5 }, { $push: { skills: "leadership" } })
// Add multiple to array
db.employees.updateOne(
{ empId: 5 },
{ $push: { skills: { $each: ["management", "analytics"] } } }
)
// Add only if not exists
db.employees.updateOne({ empId: 5 }, { $addToSet: { skills: "communication" } })
// Remove from array
db.employees.updateOne({ empId: 5 }, { $pull: { skills: "training" } })
// Query array contains element
db.employees.find({ skills: "recruiting" })
// Query array contains all elements
db.employees.find({
skills: { $all: ["communication", "recruiting"] },
})
// Query array by size
db.employees.find({ skills: { $size: 3 } })
Use deleteOne() to remove a single matching document and deleteMany() to remove all matches. Pass a filter object to specify which documents to delete. An empty filter {} with deleteMany() removes all documents in the collection. Delete operations are permanent and cannot be undone without backups.
// Delete single document
db.employees.deleteOne({ empId: 1 })
// Delete by condition
db.employees.deleteOne({ name: "Bob" })
// Delete multiple documents
db.employees.deleteMany({ dept: "Sales" })
// Delete with complex condition
db.employees.deleteMany({
salary: { $lt: 45000 },
})
// Delete all documents in collection
db.employees.deleteMany({})
Control result order and quantity with sort(), limit(), and skip(). sort() takes a document with field names and 1 (ascending) or -1 (descending). limit() restricts the number of returned documents. skip() bypasses a number of documents, enabling pagination when combined with limit().
// Sort ascending
db.employees.find({}).sort({ name: 1 })
// Sort descending
db.employees.find({}).sort({ salary: -1 })
// Sort by multiple fields
db.employees.find({}).sort({ dept: 1, salary: -1 })
// Limit results
db.employees.find({}).limit(5)
// Skip and limit (pagination)
db.employees.find({}).skip(10).limit(5)
// Combine sort, skip, limit
db.employees.find({}).sort({ salary: -1 }).skip(0).limit(3)
The aggregation pipeline processes documents through stages for complex transformations and analytics. Common stages include $match (filter), $group (aggregate), $sort, $project (reshape), $limit, and $unwind (deconstruct arrays). Each stage passes its output to the next, enabling powerful data processing workflows.
// Group and count
db.employees.aggregate([
{
$group: {
_id: "$dept",
count: { $sum: 1 },
totalSalary: { $sum: "$salary" },
avgSalary: { $avg: "$salary" },
},
},
])
// Match then group
db.employees.aggregate([
{ $match: { salary: { $gte: 50000 } } },
{
$group: {
_id: "$dept",
count: { $sum: 1 },
maxSalary: { $max: "$salary" },
},
},
{ $sort: { count: -1 } },
])
// Project (reshape documents)
db.employees.aggregate([
{
$project: {
_id: 0,
employeeName: "$name",
department: "$dept",
annualSalary: { $multiply: ["$salary", 12] },
},
},
])
// Unwind array field
db.employees.aggregate([
{ $match: { skills: { $exists: true } } },
{ $unwind: "$skills" },
{
$group: {
_id: "$skills",
count: { $sum: 1 },
},
},
])
Aggregation provides arithmetic operators ($add, $subtract, $multiply, $divide), string operators ($concat, $toUpper, $substr), and conditional operators ($cond, $ifNull, $switch). These operators transform data within $project and $group stages, enabling calculations and data reformatting.
// Arithmetic operations
db.employees.aggregate([
{
$project: {
name: 1,
salary: 1,
bonus: { $multiply: ["$salary", 0.1] },
totalComp: { $add: ["$salary", { $multiply: ["$salary", 0.1] }] },
},
},
])
// String operations
db.employees.aggregate([
{
$project: {
fullInfo: {
$concat: ["$name", " - ", "$dept"],
},
upperName: { $toUpper: "$name" },
},
},
])
// Conditional (if-then-else)
db.employees.aggregate([
{
$project: {
name: 1,
salary: 1,
level: {
$cond: {
if: { $gte: ["$salary", 60000] },
then: "Senior",
else: "Junior",
},
},
},
},
])
Indexes improve query performance by allowing MongoDB to locate documents without scanning every record. Use createIndex() to add indexes on frequently queried fields. Compound indexes cover multiple fields. Unique indexes enforce uniqueness. While indexes speed up reads, they add overhead to writes, so index strategically.
// Create single field index
db.employees.createIndex({ empId: 1 })
// Create compound index
db.employees.createIndex({ dept: 1, salary: -1 })
// Create unique index
db.employees.createIndex({ empId: 1 }, { unique: true })
// List all indexes
db.employees.getIndexes()
// Drop an index
db.employees.dropIndex({ empId: 1 })
countDocuments() returns the number of matching documents. estimatedDocumentCount() provides a fast approximate count for large collections. distinct() returns unique values for a specified field. These methods are essential for analytics, validation, and understanding data distribution.
// Count all documents
db.employees.countDocuments({})
// Count with filter
db.employees.countDocuments({ dept: "Sales" })
// Estimated count (faster for large collections)
db.employees.estimatedDocumentCount()
// Get distinct values
db.employees.distinct("dept")
// Distinct with filter
db.employees.distinct("name", { dept: "Sales" })
MongoDB supports full-text search on string content. Create a text index on fields to search, then use $text with $search to find matching documents. Text search supports phrases, negation, and relevance scoring with $meta. It's useful for searching product descriptions, articles, and user-generated content.
// Create text index
db.employees.createIndex({ name: "text", dept: "text" })
// Basic text search
db.employees.find({
$text: { $search: "Sales" },
})
// Search with phrase
db.employees.find({
$text: { $search: '"Sales Engineer"' },
})
// Exclude terms
db.employees.find({
$text: { $search: "Engineer -Senior" },
})
// Sort by text score
db.employees
.find({ $text: { $search: "Sales" } }, { score: { $meta: "textScore" } })
.sort({ score: { $meta: "textScore" } })