Using the MongoDB Shell
Open your MongoDB shell from MongoDB Compass by clicking the up arrow.
To get a list of all databases, type:
show dbs
Use Database
To use a particular database in MongoDB, type:
use <database name>
use bookstore
Note: I can use a database instance that does not exist yet. For example:
use mydb
You can see that mydb does not exit in the database yet. However, mongoDB is smart enough to create the database instance once I create a document in it.
Note: cls is used to clear screen.
GET Present Working Database (PWD)
You can get the present working Database by typing:
db
Output
bookstore
Retrieve All Collections
To get a list of all collections in a Database, you can query the database by typing:
show collections
Using the help function
To get help with all the commands available on Mongo, type:
help
Adding A New Documents
To add new document to your database from the shell, ensure you're currently in the database you would like to add the documents to. Recap
use <database name>
use bookstore
To add a document , you must:
- Reference the collection you want to add documents to.
show collections #displays all the available collection in the database
db.books #puts the books collection in an active state
db.books.insertOne({
title: "Freaky Friday",
author: "Ricky Shally",
pages:400,
genres:["Sci-Fi", "Romance"],
ratings: 8.5}) #inserts a single document in the collection
Output
{ acknowledged: true,
insertedId: ObjectId("62fff4d88b22a2a274101f40") }
This is to show that there was no error and the instance has been added to the collection successfully. To check, you can go back to your document file and check the last created file.
Note Please note that we don't necessarily have to have a collection before writing to it.
db.student.insertOne({name="Kikkie", age=18})
The above will create an instance of student and add the document in the database.
Adding Multiple Documents
You can add multiple documents at once by using:
db.books.insertMany([{
title: "Die Hard",
author: "Ricky Shalby",
pages:490,
genres:["Sci-Fi", "Adventure"],
ratings: 8.0},{
title: "Daily Dose",
author: "Rukky Shally",
pages:450,
genres:["Education", "Romance"],
ratings: 9.5}])
Retrieve Document using the Shell
To fetch documents in mongoDB shell, we use the method .find.
db.books.find() #returns the first 20 documents
it #to iterate and print the next 20
db.books.find({pages:200}) #prints out all the books with 200 pages
You can also add multiply filters
db.books.find({pages:200, genres:"Anime"}) #prints out all the books that has 200 pages and are Anime
To get only specify fields as your result
db.books.find({pages:200, genres:"Anime"}, {title:1, pages:1}) #returns title and pages of the filtered result
db.books.find({}, {title:1, pages:1}) #returns the title and pages of all the documents in the collections
db.books.findOne({pages:200, genres:"Anime"}, {title:1, pages:1}) #returns the first search result of the filter
#You can also get on object by its id
Method Chaining
You can add method to another method to enable you filter records.
Uses Cases
db.books.find().count() #counts the number of documents in the collection (book)
db.books.find({pages:250}).count() #counts the number of documents in the collection (book) that has 250 pages
db.books.find({pages:250}).limit(3) #retrieves all the documents that has 250 pages but limits the result to the first 3
Sorting Document Retrieval
You can sort the result of your document by using method .sort().
Use Cases
db.books.find().sort({title:1}) #retrieves all the documents and sorts the title in ascending order
db.books.find().sort({title:-1}) #retrieves all the documents and sorts the title in descending order
db.books.find().sort({title:-1}).limit(3) #retrieves all the documents, sort by their title in descending order and limits the result to 3
Nested Document
db.books.insertOne({title:"The way of Kings", author:"Brandon Sanderson", rating:9, pages:400, genres:["fantasy"], reviews:[{name:"Yoshi", body: "Great book"}, {name:"mario", body:"so so"}]})
if you go back and refresh, you will discover that the reviews are nested
Note: To clear the screen, type cls
Operators and Complex Queries
When using filter, this will only print out result for the exact value. For example:
db.books.find({rating:8.5})
The above will only display records that has matching rating of 8.5. To get a range of values as your filtered result, you're going to use an operator ($). For example, let's say I want to get book ratings greater than 5:
db.books.find({ rating: {$gt: 5}}) #returns the books with ratings more than 5 but not including 5
Operators in MongoDB
$gt - greater than
$ls - less than
$lte - less than or equal to
$gte - greater than or equal to
You can pass in more than one filter.For example:
db.books.find({ rating: {$gt: 5}, author:"Patrick Rothfuss"}) #filters books that are greater than 5 and whose author is "Patrick Rothfuss"
Use of OR Operator
If you would like to view result of documents if it matches a condition in the array. Like:
db.books.find({$or: [{rating:7},{rating:9}]}) #gets books that have ratings of 7 or 9
db.books.find({$or: [{pages: {$ls: 300}}, {pages: {$gt:400}}]}) #returns books with pages less than 300 and pages greater than 400
$in & $nin
The use of in and nin(not int). The in method is used to check if a condition is in the range of values specified. For example:
db.books.find({rating: {$in: [7,8,9]}}) #prints books that has rating of 7 , 8 or 9
#or
db.books.find({rating: {$or: [{rating: 7}, {rating:8}, {rating:9}]})
nin
db.books.find({rating: {$nin: [7,8,9]}}) #prints books that has rating not in 7 , 8 or 9