Connecting to the Database Instance
To initiate a session with the MongoDB server, open your system's command line interface (such as Terminal on Linux/macOS or Command Prompt on Windows). Execute the following commend to start the shell:
mongo
While working within the shell, you can clear the terminal output at any time to improve readability:
cls
Database and Collection Management
MongoDB operates on a lazy creation model; databases and collections are not fully created until data is written to them.
To switch to a specific database context (or create one if it does not exist), use the use command:
use inventory_db
To finalize the creation of the database, insert a document into a collection:
db.products.insert({"item": "notebook", "stock": 15});
To list all database currently present on the server:
show dbs;
To view the collections (analogous to tables in relational databases) within the current database:
show collections;
To permanently delete a specific collection:
db.products.drop();
To remove the entire database currently in context:
db.dropDatabase();
Inserting Documents
Data insertion into a collection can be performed using the insert method. The following example adds a new document with multiple fields:
db.products.insert({"item": "pen", "price": 1.50, "stock": 100});
Querying Data
MongoDB offers a robust querying syntax for retrieving data.
To retrieve all documents within a collection:
db.products.find();
To retrieve unique values for a specific field (e.g., finding all distinct item names):
db.products.distinct("item");
To find documents matching a specific criteria (e.g., stock equals 100):
db.products.find({"stock": 100});
Comparison Operators
Comparison operators allow for filtering based on numerical or logical conditions.
Find documents where stock is greater than 10:
db.products.find({stock: {$gt: 10}});
Find documents where stock is less than 50:
db.products.find({stock: {$lt: 50}});
Find documents where stock is greater than or equal to 20:
db.products.find({stock: {$gte: 20}});
Find documents where stock is less than or equal to 80:
db.products.find({stock: {$lte: 80}});
Find documents where price is between 5.00 and 10.00:
db.products.find({price: {$gte: 5.00, $lte: 10.00}});
Pattern Matching
Regular expressions can be used for text searching.
Find items where the name contains "pen":
db.products.find({item: /pen/});
Find items where the name starts with "note":
db.products.find({item: /^note/});
Find items where the name ends with "book":
db.products.find({item: /book$/});
Projection and Sorting
To query specific fields only (similar to SELECT item, price in SQL):
db.products.find({}, {item: 1, price: 1});
To sort results, use 1 for ascending order and -1 for descending order:
db.products.find().sort({price: 1});
Pagination and Logic
To implement pagination using limit and skip (e.g., retrieve 5 records starting after the first 10):
db.products.find().limit(5).skip(10);
To use an OR condition for queries (e.g., stock is 5 OR stock is 15):
db.products.find({$or: [{stock: 5}, {stock: 15}]});
To retrieve only the first matching document:
db.products.findOne();
To count the number of documents matching a filter (e.g., count items with price over 10):
db.products.find({price: {$gt: 10}}).count();
Modifying Data
Updates in MongoDB can target specific fields or replace entire documents.
To modify a specific field of a document (e.g., update the stock of "pen" to 50):
db.products.update({"item": "pen"}, {$set: {"stock": 50}});
By default, only the first matching document is updated. To update all matching documents, the multi option must be enabled:
db.products.update({"item": "pen"}, {$set: {"stock": 50}}, {multi: true});
To completely replace a document (excluding the $set operater), the entire content structure is provided:
db.products.update({"item": "pen"}, {"item": "fountain pen", "price": 5.00, "category": "luxury"});
To increment a numerical value (e.g., increase the price of "fountain pen" by 2):
db.products.update({item: 'fountain pen'}, {$inc: {price: 2}}, false, true);
You can combine operators, such as incrementing a value while setting another field simultaneously:
db.products.update({item: 'fountain pen'}, {$inc: {stock: 10}, $set: {status: 'restocked'}}, false, true);
Deleting Data
Removal of data can be selective or comprehensive.
To delete all documents matching a specific criteria (e.g., delete "luxury" category items):
db.products.remove({"category": "luxury"});
To ensure that only the first matching document is deleted, use the justOne flag:
db.products.remove({"category": "luxury"}, {justOne: true});