Essential MongoDB Operations: Database, Collection, and Document Management
MongoDB is a flexible, document-oriented NoSQL database that stores data in JSON-like documents. This guide covers fundamantal operations including database and collection creation, as well as the complete spectrum of Create, Read, Update, and Delete (CRUD) operations for documents.
Managing Databases in MongoDB
Creating a Database
In MongoDB, a database is implicitly created when you first store data within it. The use command switches your current context to a specified database. If the database doesn't exist, MongoDB will create it the first time you insert data into it.
Syntax
use <database_name>
Example
To create or switch to a database named devDB:
> use devDB
switched to db devDB
> db
devDB
Initially, devDB won't appear in the list of databases when you execute show dbs. It needs at least one document inserted into a collection to be physically present and visible.
> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
After inserting a document, the database becomes visible:
> db.users.insertOne({ "username": "alpha_user" })
{ "acknowledged" : true, "insertedId" : ObjectId("65f9a7e3a1b2c3d4e5f6a7b8") }
> show dbs
admin 0.000GB
config 0.000GB
devDB 0.000GB
local 0.000GB
Deleting a Database
To remove the currently active database, use the dropDatabase() command.
Syntax
db.dropDatabase()
Example
Let's delete the devDB database:
// First, ensure you are in the correct database
> use devDB
switched to db devDB
// Execute the drop command
> db.dropDatabase()
{ "dropped" : "devDB", "ok" : 1 }
// Verify deletion
> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
Managing Collections in MongoDB
Creating a Collection
Collections in MongoDB are analogous to tables in relational databases. They can be created explicitly using createCollection() or implicitly when the first document is inserted.
Syntax
db.createCollection(name, options)
Where:
name: The desired name for the collection.options: An optional document to configure collection properties.
Common options include:
Example
Creating a standard collection named products in the devDB database:
> use devDB
switched to db devDB
> db.createCollection("products")
{ "ok" : 1 }
To view existing collections:
> show collections
products
system.indexes // Automatically created for internal use
Capped Collections
Capped collections are fixed-size collections that store documents in insertion order. Once the allocated space is full, old documents are automatically overwritten by new ones, similar to a circular buffer. This is ideal for logging or caching recent data.
Creating a Capped Collection
// Create a capped collection named 'event_logs' with a size of 10MB (10,000,000 bytes)
> db.createCollection("event_logs", { capped: true, size: 10000000 })
{ "ok" : 1 }
// Or, specify a maximum number of documents (1000 in this case)
> db.createCollection("user_activity", { capped: true, size: 1000000, max: 1000 })
{ "ok" : 1 }
Checking if a Collection is Capped
> db.event_logs.isCapped()
true
Converting to a Capped Collection
An existing collection can be converted to a capped collection:
> db.runCommand({ "convertToCapped": "old_data", size: 5000000 })
{ "ok" : 1 }
Note on Capped Collections:
- Updates are permitted, but a document cannot grow beyond its original allocated size.
- Deletions of individual documents are not allowed; the entire collection must be dropped to remove all data.
- Documents are stored in insertion order, making queries that retrieve documents in this order highly efficient (e.g., for recent activity feeds).
Deleting a Collection
The drop() method removes a collection from the database.
Syntax
db.collection_name.drop()
Example
To delete the products collection:
> use devDB
switched to db devDB
> db.products.drop()
true // Returns true if the collection was successfully dropped
> show collections
event_logs
system.indexes
Managing Documents in MongoDB (CRUD Operations)
Inserting Documents
Documents are the basic unit of data in MongoDB, stored in BSON (Binary JSON) format. You can insert single or multiple documents into a collection.
Methods for Insertion (MongoDB 3.2+)
db.collection.insertOne(<document>, { writeConcern: <document> }): Inserts a single document.db.collection.insertMany([<document1>, <document2>, ...], { writeConcern: <document>, ordered: <boolean> }): Inserts multiple documents.
The older insert() and save() methods are deprecated; it's recommended to use insertOne() and insertMany().
Example: Inserting a Single Document
> use devDB
switched to db devDB
// Insert a document into the 'articles' collection
> db.articles.insertOne({
title: 'MongoDB CRUD Basics',
author: 'Data Maestro',
tags: ['mongodb', 'tutorial', 'nosql'],
views: 150,
published: new Date()
})
{
"acknowledged" : true,
"insertedId" : ObjectId("65f9a9c0a1b2c3d4e5f6a7b9")
}
If the articles collection didn't exist, it would be created automatically.
Example: Inserting Multiple Documents
> db.articles.insertMany([
{
title: 'Advanced Aggregation',
author: 'Query King',
tags: ['mongodb', 'aggregation'],
views: 300,
published: new Date("2024-03-10T10:00:00Z")
},
{
title: 'Indexing Strategies',
author: 'Index Wizard',
tags: ['mongodb', 'performance', 'indexing'],
views: 220,
published: new Date("2024-03-05T09:30:00Z")
}
])
{
"acknowledged" : true,
"insertedIds" : [
ObjectId("65f9aa56a1b2c3d4e5f6a7ba"),
ObjectId("65f9aa56a1b2c3d4e5f6a7bb")
]
}
You can also insert documents from an array variable:
> var newArticles = [];
> for (var i = 1; i <= 5; i++) {
newArticles.push({
title: "Article " + i,
author: "Anonymous",
views: i * 50
});
}
> db.articles.insertMany(newArticles)
{
"acknowledged" : true,
"insertedIds" : [
ObjectId("65f9aafd1a2b3c4d5e6f7a8b"),
ObjectId("65f9aafd1a2b3c4d5e6f7a8c"),
ObjectId("65f9aafd1a2b3c4d5e6f7a8d"),
ObjectId("65f9aafd1a2b3c4d5e6f7a8e"),
ObjectId("65f9aafd1a2b3c4d5e6f7a8f")
]
}
Updating Documents
MongoDB provides methods to modify existing documents in a collection.
db.collection.updateOne() and db.collection.updateMany()
These methods are used to update documents. updateOne() modifies a single document, while updateMany() updates all documents that match the specified criteria.
Syntax
db.collection.updateOne(
<query>,
<update>,
{
upsert: <boolean>,
writeConcern: <document>
}
)
db.collection.updateMany(
<query>,
<update>,
{
upsert: <boolean>,
writeConcern: <document>
}
)
Key parameters:
query: Filters documents to update (similar to a WHERE clause).update: Specifeis the modifications using update operators (e.g.,$set,$inc).upsert(optional): Iftrue, inserts a new document if no matching document is found. Default isfalse.
Example: Updating a Single Document
Let's update the title of an article from 'MongoDB CRUD Basics' to 'MongoDB Fundamentals'.
// Original document:
// { "_id" : ObjectId("65f9a9c0a1b2c3d4e5f6a7b9"), "title" : "MongoDB CRUD Basics", "author" : "Data Maestro", "tags" : [ "mongodb", "tutorial", "nosql" ], "views" : 150, "published" : ISODate("2024-03-19T08:00:00Z") }
> db.articles.updateOne(
{ title: 'MongoDB CRUD Basics' },
{ $set: { title: 'MongoDB Fundamentals', category: 'Database' } }
)
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
The output indicates one document was matched and modified.
Example: Updating Multiple Documents
Increment the views count by 10 for all articles by 'Anonymous'.
> db.articles.updateMany(
{ author: 'Anonymous' },
{ $inc: { views: 10 } }
)
{ "acknowledged" : true, "matchedCount" : 5, "modifiedCount" : 5 }
db.collection.replaceOne()
This method replaces an entire existing document, except for the _id field, with a new document. If _id is included in the replacement document, it must match the original _id.
> db.articles.replaceOne(
{ _id: ObjectId("65f9a9c0a1b2c3d4e5f6a7b9") },
{
title: 'Revised MongoDB Guide',
author: 'Updated Author',
summary: 'A comprehensive guide to MongoDB.',
tags: ['mongodb', 'guide'],
views: 200,
lastUpdated: new Date()
}
)
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
Deleting Documents
To remove documents from a collection, use deleteOne() or deleteMany().
db.collection.deleteOne() and db.collection.deleteMany()
Syntax
db.collection.deleteOne(
<query>,
{ writeConcern: <document> }
)
db.collection.deleteMany(
<query>,
{ writeConcern: <document> }
)
query: Specifies the criteria for documents to be deleted.
Example: Deleting a Single Document
Remove the article titled 'Article 1'.
> db.articles.deleteOne({ title: 'Article 1' })
{ "acknowledged" : true, "deletedCount" : 1 }
Example: Deleting Multiple Documents
Delete all articles by 'Anonymous' with less than 200 views.
> db.articles.deleteMany({ author: 'Anonymous', views: { $lt: 200 } })
{ "acknowledged" : true, "deletedCount" : 3 }
Example: Deleting All Documents
To clear an entire collection (similar to SQL's TRUNCATE), use an empty query document:
> db.articles.deleteMany({})
{ "acknowledged" : true, "deletedCount" : 4 } // Number depends on remaining documents
Querying Documents in MongoDB
db.collection.find() Method
The find() method is used to retrieve documents from a collection. It returns a cursor to the matching documents.
Syntax
db.collection.find(query, projection)
query(optional): A document that specifies the selection criteria. An empty document{}matches all documents.projection(optional): A document that specifies the fields to return.
Readability with .pretty()
To display results in a human-readable, formatted JSON structure, chain .pretty():
> db.articles.find().pretty()
db.collection.findOne() Method
Returns a single document that satisfeis the query criteria. If multiple documents match, it returns the first one in natural order (or index order if a sort is specified).
> db.articles.findOne({ author: 'Query King' })
Projection (Selecting Fields)
The projection parameter allows you to specify which fields to include or exclude from the query results.
- Inclusion: Specify
1for fields you want to include. The_idfield is included by default unless explicitly excluded. - Exclusion: Specify
0for fields you want to exclude.
You cannot mix inclusion and exclusion (except for excluding _id in an inclusion projection).
Example: Including specific fields
> db.articles.find({}, { title: 1, author: 1, _id: 0 }).pretty()
{ "title" : "Advanced Aggregation", "author" : "Query King" }
{ "title" : "Indexing Strategies", "author" : "Index Wizard" }
Example: Excluding specific fields
> db.articles.find({}, { tags: 0, published: 0 }).pretty()
{ "_id" : ObjectId("65f9aa56a1b2c3d4e5f6a7ba"), "title" : "Advanced Aggregation", "author" : "Query King", "views" : 300 }
Query Conditions
MongoDB uses a rich query language for filtering documents.
Equality
db.articles.find({ author: 'Data Maestro' }).pretty() // WHERE author = 'Data Maestro'
Comparison Operators
These operators are used within the query document to specify conditions:
$eq: Equal to$ne: Not equal to$gt: Greater than$gte: Greater than or equal to$lt: Less than$lte: Less than or equal to
Example: Articles with more than 200 views
> db.articles.find({ views: { $gt: 200 } }).pretty() // WHERE views > 200
Example: Articles with views between 100 and 300 (exclusive)
> db.articles.find({ views: { $gt: 100, $lt: 300 } }).pretty() // WHERE views > 100 AND views < 300
Logical Operators (AND, OR)
AND Condition
By default, if you specify multiple fields in a query document, they are combined with an implicit AND condition.
Syntax
db.collection.find({ field1: value1, field2: value2 })
Example: Articles by 'Data Maestro' with 'tutorial' tag
> db.articles.find({ author: 'Data Maestro', tags: 'tutorial' }).pretty()
// Equivalent to: WHERE author = 'Data Maestro' AND 'tutorial' IN tags
OR Condition
The $or operator allows you to specify a logical OR for queries. It takes an array of query expressions.
Syntax
db.collection.find({ $or: [{ expression1 }, { expression2 }] })
Example: Articles by 'Query King' or with more than 250 views
> db.articles.find({ $or: [{ author: 'Query King' }, { views: { $gt: 250 } }] }).pretty()
// Equivalent to: WHERE author = 'Query King' OR views > 250
Combining AND and OR
// Find articles with views > 150 AND (author = 'Index Wizard' OR tags contains 'tutorial')
> db.articles.find({
views: { $gt: 150 },
$or: [
{ author: 'Index Wizard' },
{ tags: 'tutorial' }
]
}).pretty()
Regular Expressions for Fuzzy Search
Use regular expressions for pattern matching in string fields.
Example: Find articles with titles containing "MongoDB"
db.articles.find({ title: /MongoDB/ }).pretty()
Example: Find articles with titles starting with "Advanced"
db.articles.find({ title: /^Advanced/ }).pretty()
Example: Find articles with titles ending with "Strategies"
db.articles.find({ title: /Strategies$/ }).pretty()
$type Operator
The $type operator queries documents based on their BSON data type. You can specify the type using its numeric code or string alias.
Common BSON Types and Their Codes
Example: Find documents where 'author' is a string
db.articles.find({ author: { $type: 2 } }).pretty() // Using numeric code
// OR
db.articles.find({ author: { $type: 'string' } }).pretty() // Using string alias
Limiting, Skipping, and Sorting Query Results
db.collection.find().limit() Method
The limit() method restricts the number of documents returned by a query.
Syntax
db.collection.find().limit(<number>)
Example: Retrieve the first two articles
> db.articles.find({}, { title: 1, author: 1, _id: 0 }).limit(2).pretty()
{ "title" : "Revised MongoDB Guide", "author" : "Updated Author" }
{ "title" : "Advanced Aggregation", "author" : "Query King" }
db.collection.find().skip() Method
The skip() method offsets the starting point of the query results, effectively skipping a specified number of documents.
Syntax
db.collection.find().skip(<number>)
Example: Skip the first document, then retrieve one article
// This fetches the second article
> db.articles.find({}, { title: 1, author: 1, _id: 0 }).skip(1).limit(1).pretty()
{ "title" : "Advanced Aggregation", "author" : "Query King" }
Important Note on skip() Performance:
While skip() and limit() are commonly used for pagination, skip() can be inefficient for large datasets. As the skipped number increases, MongoDB must traverse more documents before returning the desired subset, leading to degraded performance. For deep pagination in large collections, consider alternative strategies like "keyset pagination" (also known as "cursor-based pagination"). This involves querying for documents whose values for a specific sorted field are greater/less than the value of the last document from the previous page.
// Example of keyset pagination:
// If the last document on the previous page had _id: ObjectId("abc...xyz")
// db.articles.find({ _id: { $gt: ObjectId("abc...xyz") } }).sort({ _id: 1 }).limit(10)
db.collection.find().sort() Method
The sort() method orders the documents in the result set.
Syntax
db.collection.find().sort({ field_name: <order> })
Where <order> is:
1for ascending order.-1for descending order.
Example: Sort articles by views in descending order
> db.articles.find({}, { title: 1, views: 1, _id: 0 }).sort({ views: -1 }).pretty()
{ "title" : "Advanced Aggregation", "views" : 300 }
{ "title" : "Indexing Strategies", "views" : 220 }
{ "title" : "Revised MongoDB Guide", "views" : 200 }
When sort(), skip(), and limit() are used together, MongoDB executes them in a specific order: sort > skip > limit.