DEV Community

Cover image for MongoDB: Nooks and Crannies
Abayomi Ogunnusi
Abayomi Ogunnusi

Posted on

MongoDB: Nooks and Crannies

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


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.

Result:
Image description


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

Result:
Image description

Method 2:

On your terminal run mongo.exe
Result:
Image description

Now that we have confirmed MongoDB installation let's see how we can navigate around MongoDB .


To view db

 show dbs
Enter fullscreen mode Exit fullscreen mode

Image description


To view collections

show collections
Enter fullscreen mode Exit fullscreen mode

Image description


To use a db:

use [database name]
use blog
Enter fullscreen mode Exit fullscreen mode

Image description

Delete an entire db

db.dropDatabase()
Enter fullscreen mode Exit fullscreen mode

Exit out of the terminal

exit 
Ctrl + C
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode


Create collection

db.createCollection([collection name])
db.createCollection("students")
Enter fullscreen mode Exit fullscreen mode

Image description

Drop a collection

db.students.drop()
Enter fullscreen mode Exit fullscreen mode

Insert One document (a json object) into A COLLECTION

db.students.insertOne({name: "Abayomi", age:4, email:"[email protected]"})
Enter fullscreen mode Exit fullscreen mode

Image description

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"]})
Enter fullscreen mode Exit fullscreen mode

Image description


clear screen

(Ctrl + L) 
Enter fullscreen mode Exit fullscreen mode


You can generate custom id

db.students.insertOne({name: "joan", age:56, _id:256})
Enter fullscreen mode Exit fullscreen mode

Image description

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")})
Enter fullscreen mode Exit fullscreen mode

Image description


Insert multiple records using arrays of objects

db.students.insertMany([{name: "jude", age:9}, {name: "james", age:78}, {name: "amry", age:239}])
Enter fullscreen mode Exit fullscreen mode

Image description


Finding and querying Documents

Find all:

db.students.find({})
Enter fullscreen mode Exit fullscreen mode

Image description


Turn a specific field off

db.students.find({}, {_id:0})
Enter fullscreen mode Exit fullscreen mode


Limit query

db.students.find({}, {_id:0}).limit(2)
This removes all _id 
Enter fullscreen mode Exit fullscreen mode

Image description


Sort query

db.students.find({}, {_id:0}).sort({name: 1})
1 means ascending order
-1 means descending order
Enter fullscreen mode Exit fullscreen mode

The name is arranged alphabetically
Image description


Sort by multiple fields

db.students.find({}, {_id:0}).sort({age: -1, name: 1})
1= asacending order
-1 = descending order
Enter fullscreen mode Exit fullscreen mode

Image description


Find using filtering using where queries

db.students.find({age: 4}, {_id:0}).sort({name: 1, age:-1})
Enter fullscreen mode Exit fullscreen mode

Image description


Skipping entries

db.students.find().skip(1).sort({age: 1, name: 1}).limit(2)
This skips the first entry gotten from he database
Enter fullscreen mode Exit fullscreen mode

Image description


Filtering using multiple fields

db.students.find({name: "joan", age: 56})
Enter fullscreen mode Exit fullscreen mode

Image description


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
Enter fullscreen mode Exit fullscreen mode

Image description


OR operator $or logic

db.students.find({$or: [{name:"abayomi"}, {age:56}]}, {_id:0})
Enter fullscreen mode Exit fullscreen mode

Image description


Greater operator $gt than logic

db.students.find({age:{$gt: 10}})
Enter fullscreen mode Exit fullscreen mode

This gets every fields with age grater than 10.
Image description


Less than or equal to $lte

db.students.find({age:{$lte: 10}}).sort({age: -1})
Enter fullscreen mode Exit fullscreen mode

Image description

Other comparison operator worth of note: $eq, $ne,


In operator $in

db.students.find({name: {$in:["Abayomi", "joan"]}})
Enter fullscreen mode Exit fullscreen mode
  • Finds every data that has name has Abayomi and joan

Image description


Mixing complex queries

db.students.find({age:{ $gte:9, $lt:240} })
Here we are saying age is less than 10, greater than 36
Enter fullscreen mode Exit fullscreen mode

Image description


Not query

db.students.find({age:{$not:{$lte:34}}})
Enter fullscreen mode Exit fullscreen mode

* This gets all ages not less than or equal to 34

Image description


Accessing nested objects and getting specific array

db.students.find({"address.street": "ajaka makun"})
Enter fullscreen mode Exit fullscreen mode

Image description


Count documents

db.students.countDocuments({age:{$lte: 23}})
Enter fullscreen mode Exit fullscreen mode

Image description


Update data

db.students.updateOne({name: "joan"}, {$set:{name:"Joana Sisily"}})
Enter fullscreen mode Exit fullscreen mode

Image description


Update with id

db.students.updateOne({_id: ObjectId("622875510fc8edaf452c0e13")}, {$set:{age:459}})
Enter fullscreen mode Exit fullscreen mode

Image description


Find by id

db.students.findOne({_id: ObjectId("6199abeeb73c785f519a29e3")})
Enter fullscreen mode Exit fullscreen mode

* Returns null if id not found

Image description


Increment

db.students.updateOne({_id: ObjectId("622875f90fc8edaf452c0e15")}, {$inc:{age:9}})
Enter fullscreen mode Exit fullscreen mode

This increment the age value by 9, the initial value is 9, final value will be 18

Image description


#### Renaming fields

db.students.updateOne({_id: ObjectId("622875f90fc8edaf452c0e15")}, {$rename:{age:"studentAge"}}))
Enter fullscreen mode Exit fullscreen mode

Image description


Not-in operator

This negates the output

db.students.find({name: {$nin:["Abayomi", "joan"]}})
Enter fullscreen mode Exit fullscreen mode

Image description


Check if field or data exists

1) db.students.find({name: {$exists: true}})
2) db.students.find({major: {$exists: false}}, {_id:0})
Enter fullscreen mode Exit fullscreen mode
  • 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
Enter fullscreen mode Exit fullscreen mode

Image description

source


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}})
Enter fullscreen mode Exit fullscreen mode

Image description


Element Match

Check match and return a matching element in an array

db.students.find({hobbies: {$elemMatch: {$eq: "sking"}}})
Enter fullscreen mode Exit fullscreen mode

Image description


Update many records

updates all instance of the name:mimi
db.students.updateMany({name: "mimi"},{$set: {name:"miracle"}})
Enter fullscreen mode Exit fullscreen mode


Replace a field completely

db.students.replaceOne({name: "Abayomi"},{name: "Joseph abayomi", age: 90, student: true})
Enter fullscreen mode Exit fullscreen mode


Delete records

db.collectionName.action

db.students.deleteMany({}) ==> deletes all
Enter fullscreen mode Exit fullscreen mode

Image description


Delete with a query params

db.students.deleteMany({name: "xu"})
Enter fullscreen mode Exit fullscreen mode


Delete one

db.students.deleteOne({name: "xu"})
Enter fullscreen mode Exit fullscreen mode


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}
   );
Enter fullscreen mode Exit fullscreen mode

Image description


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 "}])
Enter fullscreen mode Exit fullscreen mode


Create text indexing

db.students.createIndex( { name: "text", desc: "text" } )
Enter fullscreen mode Exit fullscreen mode

Image description


db.students.find({ $text: {$search: "fair" } })
Enter fullscreen mode Exit fullscreen mode

Image description


Let's attach precedence score to search query
db.students.find(
   { $text: { $search: "Young and fair" } },
   { score: { $meta: "textScore" } }
).sort( { score: { $meta: "textScore" } } )
Enter fullscreen mode Exit fullscreen mode


Image description


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"}])

Enter fullscreen mode Exit fullscreen mode

Image description


Get total counts of books

db.students.countDocuments({item: "pen"})
Enter fullscreen mode Exit fullscreen mode

Image description


Get total amount of money spent by a student

db.students.aggregate(
     [
          {$match: {} },
          {$group: {_id: "$student", total: { $sum: "$total"} } }
     ]
)
Enter fullscreen mode Exit fullscreen mode

Image description


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}}
     ]
)
Enter fullscreen mode Exit fullscreen mode

Image description


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"} } },
     ]
)
Enter fullscreen mode Exit fullscreen mode

Image description


Resources

Bson types reference
Aggregation Reference
mongodb website
Mike Dane

Top comments (2)

Collapse
 
marcomoscatelli profile image
Marco Moscatelli

This is a great tutorial for beginners, well done!

Collapse
 
drsimplegraffiti profile image
Abayomi Ogunnusi