Youtube channel !

Be sure to visit my youtube channel

Sunday, November 17, 2019

MongoDB introduction

Let's see how to work with the non-relational database MongoDB. If you are looking for more advanced usage of MongoDB inside of a real-life application you can check this course: Learn Node.js, Express and MongoDB + JWT

 


Install the database with sudo apt install mongodb
*optional install the graphical client MongoDB compass:
https://www.mongodb.com/download-center/compass
then do dpkg -i mongodb_compass*

you can then type: mongo to get inside the interactive shell
inside you can type
show dbs
to show all the available databases:
admin   0.000GB
config  0.000GB
local   0.000GB

In mongodb we have the following structures: databases->collections->documents

use db1 switches the internal db() pointer to a different existing database or creates a new one if there is no such found. In order to actually create the database, you will need to place inside at least 1 collection.
So you can just type: db.createCollection('mycollection')
then show dbs will show your new database; the collections can be displayed using: show collections.
if we want to delete database we use: db.dropDatabase()

Since we are using unstructured data we can just place JSON object literals (named documents in MongoDb) inside the collections.
db.mycollection.insert({
field1:'value1'
})


multiple insertions:
db.mycollection.insertMany(
[
{name:'John',color:'red',position:'programmer' }
{name:'Peter',color:'green', position:'craftsman' }
{name:'Maria',color:'blue',position:'gardener' }
]
)

To display all the documents inside of a collection we could type:
db.mycollection.find().pretty()
other examples include:
db.mycollection.find({field1:'value1'})
or just get 1 field:
db.mycollection.findOne({field1:'value1'})
we can search using multiple criteria:
db.mycollection.find({field1: {$gt:5}},{_id:0})
or within subset of values:
{
_id:{ $in: [1,2]} 
db.mycollection.find({field1: {$gt:5}},{_id:0})   
 
we can aslo chain other methods to find such as limit
db.mycollection.find({field1:'value1'}).limit(5)

Update in MongoDB can be performed in two ways:
1. We search for a condition to be met, then we update the whole found document with a new document if the search condition returns a document otherwise the update fails. To update/repace entirely found docment entries we use:
update({filter_condition}, {fields_to_update})
inside filter_condition just specify JSON document key/values to search for, to be replaced by fields_to_update JSON document, for example:
db.mycollection.update({field1:'value1'},{field1:'value2'})
if we use upsert we will insert a new field if field1 search condition doesn't exist
db.mycollection.update({field1:'value1'},{field1:'value2'},{upsert:true})

2. The second way is again to search for condition, but this time to update specific fields from it - this is actually the expected familiar functionality of the MYSQL update function. We use the set operator, in order to just update specific fields:
db.mycollection.update(
{ _id: 1 },
{$inc: { quantity: 5 },
$set: {field1: "value2",}
)
An interesting thing to notice is that the documents have unique ids, so you can search by those ids in order to locate a specific document.
With inc we can increment certain fields inside the document (here the quantity field).
Example: db.mycollection.find({ _id:ObjectId("5dd0fb5988cbe5bb79e7a0e2")  } )

Notes: as filtering conditions you can use $gt:3 (which means >3) or $le:3
If you would like to rename certain keys inside the document, inside update you can us rename $rename{field1:"new_field"}
db.mycollection.update(
{ _id: 1 },
$rename{field1:"new_field"}
)with remove you can remove a document:
db.mycollection.remove(
{ _id: 1 }
)
We can have nested elements inside of the same document such as:
{
"article":{
"title":"my article",
"comments":[
                    {'title':'first comment'},
                    {'title':'second comment'}
                   ]
}
}

like so:
db.mycollection.insert(
{
"title":"my article",
"comments":[{'title':'first comment'},{'title':'second comment'}]
});

In order to search inside the comments we can use:
db.mycollection.find(  
{  
comments:{  $elemMatch:{ title:'first comment' }  }  
}
)
Keep in mind that when searching this way you have to specify exact match for the text fields. If you would like to perform full-text search you can place indexes on the fields you would like to search:
db.mycollection.createIndex({title:'text'})

Let's now insert multiple documents:
db.mycollection.insertMany(

{"_id":1,  "title":"my newest"},
{ "_id":2, "title":"my article 1"},
{ "_id":3, "title":"my article 2"},
{ "_id":4, "title":"my article 3"},
{ "_id":5, "title":"my article 4"},
{ "_id":6, "title":"my article 5"},  
]
);

*Optional:
db.mycollection.getIndexes() will display the indexes
from there you can find the name of the index and use: db.mycollection.dropIndex('comments_text') to remove it.
 

then use db.mycollection.find(  {  $text:{  $search: "\"article \""  }  })
to search inside the indexed field. You should escape the search string \" if doing a phrase search.
Note: In order to ensure that Fulltext search to work, you should aim for longer than 4 characters words to have inside the database!

Congratulations, you now know some of the basics when working with MongoDB!

Subscribe To My Channel for updates

Integrating AI code helpers into Visual Studio Code

In this guide, we’ll walk through setting up a local AI-powered coding assistant within Visual Studio Code (VS Code). By leveraging tools s...