MongoDB: Nooks and Crannies

MongoDB: Nooks and Crannies

MongoDb: Flexible Database

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

Image description




To view collections

show collections

Image description




To use a db:

use [database name]
use blog

Image description

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

Image description


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

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

Image description


clear screen

(Ctrl + L)


You can generate custom id

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

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

Image description


Insert multiple records using arrays of objects

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

Image description


Finding and querying Documents

Find all:

db.students.find({})

Image description


Turn a specific field off

db.students.find({}, {_id:0})


Limit query

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

Image description


Sort query

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

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

Image description


Find using filtering using where queries

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

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

Image description


Filtering using multiple fields

db.students.find({name: "joan", age: 56})

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

Image description


OR operator $or logic

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

Image description


Greater operator $gt than logic

db.students.find({age:{$gt: 10}})

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

Image description

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

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

Image description


Not query

db.students.find({age:{$not:{$lte:34}}})

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

Image description


Count documents

db.students.countDocuments({age:{$lte: 23}})

Image description


Update data

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

Image description


Update with id

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

Image description


Find by id

db.students.findOne({_id: ObjectId("6199abeeb73c785f519a29e3")})

* Returns null if id not found

Image description


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

Image description


Renaming fields

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

Image description


Not-in operator

This negates the output

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

Image description


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

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

Image description


Element Match

Check match and return a matching element in an array

db.students.find({hobbies: {$elemMatch: {$eq: "sking"}}})

Image description


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

Image description


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}
   );

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


Create text indexing

db.students.createIndex( { name: "text", desc: "text" } )

Image description


db.students.find({ $text: {$search: "fair" } })

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


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

Image description


Get total counts of books

db.students.countDocuments({item: "pen"})

Image description


Get total amount of money spent by a student

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

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

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

Image description


Resources

Bson types reference Aggregation Reference mongodb website Mike Dane