Basic MongoDB CRUD Operations
Two common methods to start the MongoDB service:
- Press Windows + R, enter
services.msc, locate the MongoDB service, then start it manually. - Open an elevated Command Prompt, run
net start mongodbto start the service.
Next, launch the MongoDB shell: Run the mongo command in a terminal to access the MongoDB command interface. If you encounter a command not found error, add the MongoDB bin directory to your system's PATH environment variable.
Create a Database
Use the use <database-name> command to switch to or create a new database. If the specified database does not exist, MongoDB will automatically create it when you first store data in it.
Example:
use ecommerceDB
Note: Running
show dbswill not display empty databases, so the newly createdecommerceDBwill not show up until you insert data into a collection within it.
Drop a Database
To delete the currently selected database, run the db.dropDatabase() method. This operates on the databace you have switched to with the use command.
Create a Collection
Collections are equivalent to relational database tables. Use db.createCollection("<collection-name>") to create a new collection.
Example:
db.createCollection("customerColl")
Drop a Collection
To delete a specific collection, call the .drop() method on the collection object:
db.customerColl.drop()
List All Collections
To view all collections in the currently selected database, run the show collections command.
Insert Documents
Documents are the equivalent of rows in relational databases. MongoDB provides several methods to insert documents:
db.collection.insertOne(): Inserts a single document. If an_idprimary key is already present, it will update the existing document; otherwise, it inserts a new one.db.collection.insertMany(): Inserts multiple documents at once. Supports optional write concern and ordered insertion flags.db.collection.insert(): Inserts one or more documents. If a duplicate_idis detected, it will throw a duplicate key exception and abort the insertion.
Syntax for insertOne()
db.collection.insertOne(
<document>,
{
writeConcern: <document>
}
)
Syntax for insertMany()
db.collection.insertMany(
[ <document 1> , <document 2>, ... ],
{
writeConcern: <document>,
ordered: <boolean>
}
)
writeConcern: Defines the write acknowledgment level. Defaults to1(acknowledged write), set to0for no acknowledgment.ordered: Specifies whether to insert documents in the given order. Defaults totrue; if set tofalse, MongoDB will attempt to insert all documents regardless of order.
Example Insertion
db.customerColl.insertOne({
username: "sarahlee",
email: "sarah@example.com",
signupDate: new Date()
})
Update Documents
Use the db.collection.update() method to modify existing documents in a colllection.
Standard Syntax
db.collection.update(
<query-filter>,
<update-object>,
{
upsert: <boolean>,
multi: <boolean>,
writeConcern: <document>
}
)
Parameter Explanations
query-filter: The filter to match documents to udpate, equivalent to theWHEREclause in SQL.update-object: The update operations to apply, including update operators like$set.upsert: If set totrue, inserts a new document if no matching documents are found. Defaults tofalse.multi: If set totrue, updates all matching documents; defaults tofalse, only updating the first matching document.
Example Update
db.customerColl.update(
{ location: "Shanghai" },
{ $set: { membershipTier: "Premium" } }
)
The $set operator updates or adds the specified fields to the matched documents.
You can also format query results for readability using the .pretty() method:
db.customerColl.find().pretty()
Without .pretty(), results will be displayed as a single horizontal line.
There is an alternative update method using save():
db.collection.save(
<document>,
{
writeConcern: <document>
}
)
The save() method replaces the existing document if the provided _id exists, otherwise inserts a new document.
To be continued, with more content coming soon.