Database manipulation and querying can be time-consuming, and as developers, we require a database that is both flexible and capable of speeding up our development process.
Today, we'll look at how to use MongoDB, one of the most popular NoSQL databases.
Table Of Content
- Installation and Setup
- Starting MongoDB Server
- Database commands
- Data Types in Mongodb
- Performing operations on Collections
- Query documents
- Operators
- Mixing complex queries
- Aggregation
- Resources
Prerequisite
🎯 MongoDB and mongoshell installed. Download
🎯 Add MongoDB path to your environment variable
Checking MongoDB is installed correctly
To check if you have MongoDB correctly installed and added to your environment variable, run mongo --version in your terminal.
Start a MongoDB server
Method 1:
You can also run mongosh on your terminal if you install the new mongo shell. Click here to download
Method 2:
On your terminal run mongo.exe
Result:
Now that we have confirmed MongoDB
installation let's see how we can navigate around MongoDB .
To view db
show dbs
To view collections
show collections
To use a db:
use [database name]
use blog
Delete an entire db
db.dropDatabase()
Exit out of the terminal
exit
Ctrl + C
Data Types in Mongodb
Mongodb uses BSON i.e key value pairs
{
string:"strings",
int:405,
double: 3.565,
boolean: true, || false
array: [1,23,4,5]
object:{attr1: "", attr2:"",attr3:""},
date:new Date("YYYY-mm-dd"),
no_value: null
}
Create collection
db.createCollection([collection name])
db.createCollection("students")
Drop a collection
db.students.drop()
Insert One document (a json object) into A COLLECTION
db.students.insertOne({name: "Abayomi", age:4, email:"joe@gmail.com"})
Result: The _id
is the unique identifier.
Breakdown: the {name: "Abayomi"} is called a Document and it lives inside the collection i.e every object stored in a collection in db is called a document.
Insert nested object
db.students.insertOne({name: "yomi", age:56, address:{street:"ajaka makun"}, hobbies:["gyming"]})
clear screen
(Ctrl + L)
You can generate custom id
db.students.insertOne({name: "joan", age:56, _id:256})
Adding arrays
db.students.insertOne({name: "jinx", hobbies: ["sking", "fighting"]})
db.students.insertOne({name: "jinx", hobbies: ["sking", "fighting"], contact: 0808083423, startDate: new Date("2020-08-89")})
Insert multiple records using arrays of objects
db.students.insertMany([{name: "jude", age:9}, {name: "james", age:78}, {name: "amry", age:239}])
Finding and querying Documents
Find all:
db.students.find({})
Turn a specific field off
db.students.find({}, {_id:0})
Limit query
db.students.find({}, {_id:0}).limit(2)
This removes all _id
Sort query
db.students.find({}, {_id:0}).sort({name: 1})
1 means ascending order
-1 means descending order
The name is arranged alphabetically
Sort by multiple fields
db.students.find({}, {_id:0}).sort({age: -1, name: 1})
1= asacending order
-1 = descending order
Find using filtering using where queries
db.students.find({age: 4}, {_id:0}).sort({name: 1, age:-1})
Skipping entries
db.students.find().skip(1).sort({age: 1, name: 1}).limit(2)
This skips the first entry gotten from he database
Filtering using multiple fields
db.students.find({name: "joan", age: 56})
Select syntax
db.students.find({}, {name: 1, age: 1, _id: 0})
This selects only the name and age property it will not populate other info like address and hobbies and also omits the _id property
OR operator $or logic
db.students.find({$or: [{name:"abayomi"}, {age:56}]}, {_id:0})
Greater operator $gt than logic
db.students.find({age:{$gt: 10}})
This gets every fields with age grater than 10.
Less than or equal to $lte
db.students.find({age:{$lte: 10}}).sort({age: -1})
Other comparison operator worth of note: $eq, $ne,
In operator $in
db.students.find({name: {$in:["Abayomi", "joan"]}})
- Finds every data that has
name
has Abayomi and joan
Mixing complex queries
db.students.find({age:{ $gte:9, $lt:240} })
Here we are saying age is less than 10, greater than 36
Not query
db.students.find({age:{$not:{$lte:34}}})
* This gets all ages not less than or equal to 34
Accessing nested objects and getting specific array
db.students.find({"address.street": "ajaka makun"})
Count documents
db.students.countDocuments({age:{$lte: 23}})
Update data
db.students.updateOne({name: "joan"}, {$set:{name:"Joana Sisily"}})
Update with id
db.students.updateOne({_id: ObjectId("622875510fc8edaf452c0e13")}, {$set:{age:459}})
Find by id
db.students.findOne({_id: ObjectId("6199abeeb73c785f519a29e3")})
* Returns null
if id not found
Increment
db.students.updateOne({_id: ObjectId("622875f90fc8edaf452c0e15")}, {$inc:{age:9}})
This increment the age value by 9, the initial value is 9, final value will be 18
#### Renaming fields
db.students.updateOne({_id: ObjectId("622875f90fc8edaf452c0e15")}, {$rename:{age:"studentAge"}}))
Not-in operator
This negates the output
db.students.find({name: {$nin:["Abayomi", "joan"]}})
Check if field or data exists
1) db.students.find({name: {$exists: true}})
2) db.students.find({major: {$exists: false}}, {_id:0})
- Ex 2: Returns nothing
BSON indexing
To return data type using BSON indexing i.e strings is 2.
db.students.find({name: {$type: 2}})
2 means strings: this will return all name fields that is strings
Check specific array entries
i.e target specific element in an array
Get arrays size
i.e if an elements has 4 , 5, 6 etc elem in it
db.students.find({hobbies: {$size: 2}})
Element Match
Check match and return a matching element in an array
db.students.find({hobbies: {$elemMatch: {$eq: "sking"}}})
Update many records
updates all instance of the name:mimi
db.students.updateMany({name: "mimi"},{$set: {name:"miracle"}})
Replace a field completely
db.students.replaceOne({name: "Abayomi"},{name: "Joseph abayomi", age: 90, student: true})
Delete records
db.collectionName.action
db.students.deleteMany({}) ==> deletes all
Delete with a query params
db.students.deleteMany({name: "xu"})
Delete one
db.students.deleteOne({name: "xu"})
Bulk Write
perform multiple action update, delete, insert
in one command
db.students.bulkWrite(
[
{ insertOne :
{
"document" :
{
name: "James", occupation: "Developer"
}
}
},
{ insertOne :
{
"document" :
{
name: "Travesy", occupation: "backend"
}
}
},
{ updateOne :
{
filter : { name : "James" },
update : { $set : { occupation: "content-writer"} }
}
},
{ deleteOne :
{ filter : { name : "Abayomi"} }
},
{ replaceOne :
{
filter : { name : "James" },
replacement : { name: "James Bond", }
}
}
],
{ordered: false}
);
Text indexing
This is synonymous to a search bar on the client-side
db.students.insertMany([{name: "John", desc: "Young and fair"},{name: "Doe", desc: "fair but young and silly"}, {name: "Dare", desc: "young and beautiful "}])
Create text indexing
db.students.createIndex( { name: "text", desc: "text" } )
db.students.find({ $text: {$search: "fair" } })
Let's attach precedence score to search query
db.students.find(
{ $text: { $search: "Young and fair" } },
{ score: { $meta: "textScore" } }
).sort( { score: { $meta: "textScore" } } )
Aggregation
db.students.insertMany([{item : "pencil", total: 10.75, student: "Wick"}, {item : "pen", total: 50, student: "John"}, {item : "book", total: 11.33, student: "Thanos"}, {item : "ruler", total: 8.50, student: "Thanos"}, {item : "book", total: 4.75, student: "James"}, {item : "pen", total: 4.75, student: "Wick"}, {item : "bag", total: 4.75, studstudent: "John"}])
Get total counts of books
db.students.countDocuments({item: "pen"})
Get total amount of money spent by a student
db.students.aggregate(
[
{$match: {} },
{$group: {_id: "$student", total: { $sum: "$total"} } }
]
)
Find how much has been spent on each item and sort it by price
db.students.aggregate(
[
{$match: {} },
{$group: {_id: "$item", total: { $sum: "$total"} } },
{$sort: {total: -1}}
]
)
Find how much money each customer has spent on book and pen
db.students.aggregate(
[
{$match: {item: {$in: ["book", "pen"]} } },
{$group: {_id: "$item", total: { $sum: "$total"} } },
]
)
Resources
Bson types reference
Aggregation Reference
mongodb website
Mike Dane
Top comments (2)
This is a great tutorial for beginners, well done!
@moscatellimarco Thanks