MongoDB: Nooks and Crannies
Tags: mongodb, beginners, devjournal, tutorial
Published: 2022-03-09 12:37:53


 
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. 
<br />
<br />
#### Table Of Content
* [Installation and Setup](#install)
* [Starting MongoDB Server](#start)
* [Database commands](#commands)
* [Data Types in Mongodb](#datatypes)
* Performing operations on Collections
    * [Create a collection](#create)
    * [Drop a collection](#dropcollection)
    * [Insert a document into a collection](#insertdoc)
    * [Insert nested object into a collection](#nestedObject)
    * [Clear Screen](#clearscreen)
    * [Generating Custom Id](#custom)
    * [Inserting multiple records using arrays of objects](#multiple)
* Query documents
    * [Find all](#findall)
    * [Turn a specific field off in mongodb](#off)
    * [Limit Clause](#limit)
    * [Sort Clause](#sort)
    * [Sort by multiple fields](#sortm)
    * [Skipping entries](#skip)
    * [Filtering using multiple fields](#filtering)
    * [Select syntax](#syntax)
*  Operators
    * [OR operator $or logic](#oroperator)
    * [Greater operator $gt than logic](#greaterdan)
    * [Less than or equal to $lte](#lessthanequal)
    * [In operator $in](#inoperator)
* Mixing complex queries
    * [not query](#notquery)
    * [Accessing nested objects and getting specific array](#accessnested)
* [Aggregation](#aggregation)
* [Resources](#resources)

<br />
---

#### Prerequisite <a name='install'></a>
🎯 MongoDB and mongoshell installed. [Download](https://www.mongodb.com/products)

🎯 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 <kbd>mongo --version </kbd> in your terminal.

Result:
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rxdkqxjmk7m9rseq17wd.PNG)

***

<br />
<br />
#### Start a MongoDB server <a name='start'></a>
#### _Method 1:_
You can also run <kbd>mongosh</kbd> on your terminal if you install the new mongo shell. Click [here](https://www.mongodb.com/products/shell)   to download 

Result:
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u7u9xsjbs1o9bs3kfd11.PNG)
 
#### _Method 2:_
On your terminal run <kbd>mongo.exe</kbd>
Result: 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k7l0e9ylrx4oouxw305i.PNG)
 
Now that we have confirmed `MongoDB ` installation let's see how we can navigate around MongoDB .

---

<br />
<br />
#### To view db <a name= 'commands'></a>

```javascript
 show dbs
```
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r1xn0emniphd88wy0ukl.png)
 
---

<br />
<br />
#### To view collections
```
show collections
```
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oyen1xtp14gqigkuj59n.png)
 
---

<br />
<br />
#### To use a db: 
```Javascript
use [database name]
use blog
```
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3bubzammhtb6wutz5ubq.png)
 

#### Delete an entire db
```
db.dropDatabase()
```

#### Exit out of the terminal
```javascript
exit 
Ctrl + C
```
 
---
<br />
#### Data Types in Mongodb <a name = "datatypes"><a/>
Mongodb uses BSON i.e key value pairs
```javascript
{
    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
}
```
<br />
---

#### Create collection <a name='create'></a>
```Javascript
db.createCollection([collection name])
db.createCollection("students")
```
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kiqx2n8ajnf2zx8py22r.png)


<br />
#### Drop a collection <a name='dropcollection'></a>
```Javascript
db.students.drop()
```

#### Insert One document (a json object) into A COLLECTION <a name='insertdoc'></a>
 ```Javascript
db.students.insertOne({name: "Abayomi", age:4, email:"joe@gmail.com"})
```
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k09l9shral6yj2e5vslx.png)

Result: The `_id` is the unique identifier.

<mark>Breakdown</mark>: 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.

---
<br />

#### Insert nested object <a name = "nestedObject"></a>

```javascript
db.students.insertOne({name: "yomi", age:56, address:{street:"ajaka makun"}, hobbies:["gyming"]})
```
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1h3p3x17e0zkq1fvs0l4.png)
 
 <br />
---

#### clear screen  <a name ="clearscreen"></a>
```javascript
(Ctrl + L) 
```
<br />
---

#### You can generate custom id <a name='custom'></a>
```Javascript
db.students.insertOne({name: "joan", age:56, _id:256})
```
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uco02gn7upqh8adcluxd.png)
 <br />

#### Adding arrays
```Javascript
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ciummbo4qgxkct42fuyy.png)
<br />
---
 
#### Insert multiple records using arrays of objects  <a name='multiple'></a>
```Javascript
db.students.insertMany([{name: "jude", age:9}, {name: "james", age:78}, {name: "amry", age:239}])
```
---
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wi87jfv00qqmqg34e6uf.png)
 
<br />
---

#### Finding  and querying Documents <a name = "findall"></a>

#### Find all:
```Javascript
db.students.find({})
```
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uk2gdvmtwlrk7uijxdjg.png)
 
 <br />
---
#### Turn a specific field off <a name = "off"></a>
```Javascript
db.students.find({}, {_id:0})
```
<br />
---

#### Limit query <a name= "limit"></a>
```Javascript
db.students.find({}, {_id:0}).limit(2)
This removes all _id 
```
---
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1htnxjkpc786pce3ylu6.png)
 
<br />
---

#### Sort query <a name='sort'></a>
```Javascript
db.students.find({}, {_id:0}).sort({name: 1})
1 means ascending order
-1 means descending order
```
The name is arranged alphabetically
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/temwyuw08vkfrq8pm0oh.png)
 <br />
---

#### Sort by multiple fields <a name= "sortm"></a>
```Javascript
db.students.find({}, {_id:0}).sort({age: -1, name: 1})
1= asacending order
-1 = descending order
```
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/08aoea3xwz4vnfsg3xz5.png)

<br />
---
#### Find using filtering using where queries <a name= "filtering"></a>
```Javascript
db.students.find({age: 4}, {_id:0}).sort({name: 1, age:-1})
```
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yvt0oguja3mxb2nq0145.png)
 
 <br />
---

#### Skipping entries <a name = "skip"></a>

```javascript
db.students.find().skip(1).sort({age: 1, name: 1}).limit(2)
This skips the first entry gotten from he database
```
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/18nfuih2rogxhrwifiba.png)
 
<br />
---

#### Filtering using multiple fields
```Javascript
db.students.find({name: "joan", age: 56})
```
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n9vmhe35p1wwpao28r94.png)
 
<br />
---

#### Select syntax  <a name= "syntax"></a>
```javascript
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/25x0v2frflkq8tjhc2ff.png)
 
 <br />
---

#### OR operator <kbd>$or</kbd> logic <a name = "oroperator"></a>
```Javascript
db.students.find({$or: [{name:"abayomi"}, {age:56}]}, {_id:0})
```
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rztehdzcrad3nd7dhpmg.png)
 
 <br />
---
#### Greater operator <kbd>$gt</kbd> than logic <a name = "greaterdan"></a>
```Javascript
db.students.find({age:{$gt: 10}})
```
This gets every fields with age grater than 10.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4tz7e7086kivbwfs10hh.png)

<br /> 
---
#### Less than or equal to <kbd>$lte</kbd> <a name = "lessthanequal"></a>
```Javascript
db.students.find({age:{$lte: 10}}).sort({age: -1})
```
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mk3olertvx9xqwajep4a.png)
 
Other comparison operator worth of note: `$eq, $ne, `

<br />
---

#### In operator <kbd>$in<kbd> <a name = "inoperator"></a>
```Javascript
db.students.find({name: {$in:["Abayomi", "joan"]}})
```
* Finds every data that has `name` has <kbd>Abayomi</kbd> and <kbd>joan</kbd>

---
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/318dki09v9vmxarg0a8g.png)
 

<br />
---

#### Mixing complex queries

```javascript
db.students.find({age:{ $gte:9, $lt:240} })
Here we are saying age is less than 10, greater than 36
```
---
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0oi7a3w8wm2iqxgij2yb.png)
 
<br />
---

#### Not query <a name= "notquery"></a>

```javascript
db.students.find({age:{$not:{$lte:34}}})
```
* This gets all ages not less than or equal to 34
---
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hzftayojhwq039j92a64.png)
 
<br />
---

#### Accessing nested objects and getting specific array <a name = "accessnested"></a>

```javascript
db.students.find({"address.street": "ajaka makun"})
```
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v7ozs6j5nfza9nneelzs.png)
 
<br />
---

#### Count documents

```
db.students.countDocuments({age:{$lte: 23}})
```
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zwe3bt8gd1w3mkab0ib7.png)
 
<br />
---

### Update data

```Javascript
db.students.updateOne({name: "joan"}, {$set:{name:"Joana Sisily"}})
```
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vsztltzhtan7rhhhzsw7.png)
 
<br />
---

#### Update with id

```Javscript
db.students.updateOne({_id: ObjectId("622875510fc8edaf452c0e13")}, {$set:{age:459}})
```
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q92kdmyrwr5da37gqzir.png)

<br /> 
---


#### Find by id

```
db.students.findOne({_id: ObjectId("6199abeeb73c785f519a29e3")})
```
* Returns `null` if id not found
---
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hlrpronpobe1eegmg3t1.png)
 
<br />
---

#### Increment

```javscript
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/it7hafzdysiqaby5vxtt.png)

<br /> 
---

 #### Renaming fields

```javscript
db.students.updateOne({_id: ObjectId("622875f90fc8edaf452c0e15")}, {$rename:{age:"studentAge"}}))
```
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5s5m1tq8nhnyjx762m96.png)
 
<br />
---

#### Not-in operator
This negates the output

```Javascript
db.students.find({name: {$nin:["Abayomi", "joan"]}})
```
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y36lu8bhpmxjtxhzdl0e.png)

---

 


#### Check if field or data exists
```Javascript
1) db.students.find({name: {$exists: true}})
2) db.students.find({major: {$exists: false}}, {_id:0})
```
* Ex 2: Returns nothing

<br />
---

### BSON indexing 
To return data type using BSON indexing i.e strings is 2.
```Javascript
db.students.find({name: {$type: 2}})
2 means strings: this will return all name fields that is strings
```
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tdzzwz07x39y1ivgeto6.png)
 

[source](https://www.youtube.com/redirect?event=video_description&redir_token=QUFFLUhqbHA3RUZ1blhvSFRiVFpVOTNEallXMkdjaXNGZ3xBQ3Jtc0tuSkR3UnpmVjhpV3dOVk93ZkZ0SFN4bGt0Y0ZqSi1TajJoajBUOEI0bWMzOVliam9hUHQtMVZkZUxWV1Znd3p4d1lrRDhuWEJrZEtFcjQ2TE5tMlBYUllCWm9hVVVPUWJLM29MMHFZa2Y4dGpnQ1ZXTQ&q=https%3A%2F%2Fdocs.mongodb.com%2Fmanual%2Freference%2Fbson-types%2F)

<br />
---

#### 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
```Javascript
db.students.find({hobbies: {$size: 2}})
```
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xgdzpjlwr5wkzp06pyh9.png)
 
<br />
---

#### Element Match
Check match and return a matching element in an array
```Javascript
db.students.find({hobbies: {$elemMatch: {$eq: "sking"}}})
```
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gv2wl4wgbpfxiwdxvf1o.png)

<br />
---

#### Update many records

```javascript
updates all instance of the name:mimi
db.students.updateMany({name: "mimi"},{$set: {name:"miracle"}})
```
<br />
---

#### Replace a field completely
```Javascript
db.students.replaceOne({name: "Abayomi"},{name: "Joseph abayomi", age: 90, student: true})
```
<br />
---

#### Delete records
db.collectionName.action
```Javascript
db.students.deleteMany({}) ==> deletes all
```
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/131srvvba9y1s1b5y5dv.png)

<br />
---

#### Delete with a query params
```Javascript
db.students.deleteMany({name: "xu"})
```
<br />
---

#### Delete one
```Javascript
db.students.deleteOne({name: "xu"})
```
<br />
---

#### Bulk Write 
perform multiple action `update, delete, insert` in one command

```Javascript
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d0lip7le98z2x7n47s6r.png)
 
 <br />
---

#### Text indexing
This is synonymous to a search bar on the client-side
```Javascript

db.students.insertMany([{name: "John", desc: "Young and fair"},{name: "Doe", desc: "fair but young and silly"}, {name: "Dare", desc: "young and beautiful "}])
```
<br />
---

#### Create text indexing

```Javascript
db.students.createIndex( { name: "text", desc: "text" } )
```
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c495y6hzcw46z21cmj2p.png)

<br />
---

```Javascript
db.students.find({ $text: {$search: "fair" } })
```
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0b2leuwayj4pxhw0q2wv.png)
 
---

```Javascript
Let's attach precedence score to search query
db.students.find(
   { $text: { $search: "Young and fair" } },
   { score: { $meta: "textScore" } }
).sort( { score: { $meta: "textScore" } } )
```
<br />
---

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uxvqrs3iioajg82bc44l.png)

<br /> 
---

#### Aggregation <a name = "aggregation"></a>
```Javascript

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n3mjwbb2sbap0ktbb5rf.png)

<br />
---

#### Get total counts of books
```Javascript
db.students.countDocuments({item: "pen"})
```
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jr9aa05pdky3cpm28mii.png)
 
<br />
---

#### Get total amount of money spent by a student
```Javascript
db.students.aggregate(
     [
          {$match: {} },
          {$group: {_id: "$student", total: { $sum: "$total"} } }
     ]
)
```
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fu7zolkafr3nl68qz8v7.png)
 
<br />
---

#### Find how much has been spent on each item and sort it by price
```Javascript
db.students.aggregate(
     [
          {$match: {} },
          {$group: {_id: "$item", total: { $sum: "$total"} } },
          {$sort: {total: -1}}
     ]
)
```
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ndzn1ja1esmk703578ke.png)
 
<br />
---

#### Find how much money each customer has spent on book and pen
```Javascript
db.students.aggregate(
     [
          {$match: {item: {$in: ["book", "pen"]} } },
          {$group: {_id: "$item", total: { $sum: "$total"} } },
     ]
)
```
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gxgbixaydxuxijbtmih2.png)
 <br />
---


#### Resources <a name='resources'></a>
[Bson types reference](https://docs.mongodb.com/manual/reference/bson-types/)
[Aggregation Reference](https://docs.mongodb.com/manual/reference/operator/aggregation/)
[mongodb website](https://www.mongodb.com/)
[Mike Dane](https://www.mikedane.com/databases/mongodb/)