MongoDB with Spring Boot Crash Course - Full Tutorial

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey what's up everyone and welcome to daily code buffer in this video we are going to see about mongodb and how to use mongodb in your springboard application so first let's see why we need to use mongodb and what are the advantages so what is mongodb so mongodb is a nosql database which allows us to store the data in the nosql format means in the document format so it's a non-structure data format that we can store in the mongodb and it's highly scalable as well so if we take the relational database in the relational database there is a complete structure and within that structure we have to store our data but in nosql in mongodb there is no structure defined we can store the unstructured data we can store the data in a document format in a json format very easily and as it's highly scalable we can scale those applications very efficiently as well and we can serve millions of users so generally no sql databases are used when you have to store the non-structural data means you have to store in the document format so if you see this json format this is how the data would be stored directly in your mongodb but in the relational databases if when you're using oracle mysql postgres you cannot store the data that way so that's the advantages for it and we will see how we can store all those data using the springboard application we are going to see a complete crud application and we are also going to see the some of the aggregations that we can use using the mongodb so let's quickly create our springboot application and let's implement the mongodb so first let me go to the new project you can create the project using the intellij idea as well and you can also create using this spring initializer i'll add the spring initializers link in the description below so you just go there and click on the new project and here we can add the project name so i'll just define springboot mongodb okay and i'll select the location here and my language is java the project type is may 1 the group id can select as daily code buffer third effect has springboot mongodb package name as springboot mongodb jdk is 11 and java i'll be using 11 and my packaging would be of char type so click on next here i need to add the spring web then i'll add the lumbar then here i'll add the springboot mongodb dependency and then i'll click on create to create our project so you can see that your project is created but before that let's install the mongodb as well so to install the mongodb make sure that you have docker installed in your machine because that's the easiest way to install mongodb in your local system but if you want to use the cloud you can go ahead and use the mongodb cloud that is the atlas there you will be able to easily create the account and you will get the credentials from there and you will be also able to create the database so whichever is preferable for you you can go ahead and use that here i'll show you how to install in the local machine so once the docker is installed in the machine make sure that docker desktop is installed either you are using mac windows or linux wherever you are using just install locker and run this particular command so here you can see that this command is fairly simple where we are just running the docker run command and we are giving the name of the container here you can give the name of the container i'll give mongodb okay and then here you can see that we are passing some of the environment variables that is the init db root username and the password so whatever the username and password you want to give you can give the credentials over here and you can see we are also passing the port information so my mongodb in my local would be running in port number 27017 and is the image name that i want to download so once you run this command mongodb will be installed in your machine you can see this way once you once you run this command you can directly go here and see docker images so let me just start the docker first okay i'll start my docker so your docker is not started make sure the docker is started and it's all perfectly fine then you'll be able to run the command so here you can see that i have already installed mongodb that's why i am getting this particular mongodb as an image here i can just start from here directly okay you can see that it started and here i can see the images so if i run docker images you can see that i am getting the as the image here and if i do docker ps and you can see that my mongodb is running here and it's running on port 27017 okay so my mongodb is installed and it's running completely fine if you want a gui for that what you can do is you can go to the browser and you can search for studio 3d go to studio 3d and you can download this studio3 this is the gui for your mongodb okay you can go ahead and download for your particular operating system i have already downloaded so what i'll do i will just start the studio 3d so just start studio 3d here so you can see that it's asking to connect but if you're not connected to your system what you can do is you can go to the new connection here and here you can give the url i will add the url as well in the description below so you can directly add it but what you can do you can see that i will just show you here so what i have added is i have added this server as 127.0.0.1 that is your local host and then i have given the port information as well that is 27017 and in the authentication i have given the basic authentication you have to select the basic authentication and give your username and password whatever you have added while creating the mongodb image so give that username and password and then in the authentication db give us admin once you do that you can save the connection and you can connect from here so you can see that i have connected here and you can see i'm able to connect to my mongodb so that's the only thing you have to do now we will go to our springboot application and we will go to the our src main resources and application.properties here we will add the configuration so that our springboard application can connect to our mongodb so yeah you can see that it's very simple we just added spring data mongodb authentication database that is admin we also saw in the studio 3d that it was admin and i have added username and password that is admin and password the database name i will be creating demo as a database you can give any database name the port number we have to give like which particular portable we want to connect and the host information where we want to connect as we are connecting in our localhost you can give localhost or you can give the ip that is 127.0.0.1 whichever you prefer that is fine so we have just given this configuration details here now what we will do is we will start our applications now let's talk about internet security with more than 5200 servers amazing speed and one click connect not vpn gives you the best features and security as a techie we know how much important it is to secure our data and identity with node vpn's disk class servers and end-to-end encryption everything is secure which routes via their servers so no one will know your ip addresses and if you want you can route through to vpn servers to double down on production and also it enables all the content on netflix or amazon prime you can just change the server and the content or your favorite shows available on that location will be available i use node vpn on all my devices so if you are interested go to this link or use the coupon code dcb to get a 2 year plan plus a bonus gift with a huge discount now back to the video so now let's first create the packages and then we will build our application so let me just go here in the java let me create the packages i'll create the collection package where we'll store our all the collections that will interact with our mongodb so this will be inside this collection and after the collection i will create one controller then i'll create a service then i'll create the repository okay so these are the things that we are going to build so now let's first create the collection so we are going to work with the person entities so we'll be creating a person and the person will be having few of the properties like name person id name and the address information and all those things hobbies and everything so let's first go ahead and create the person so i'll just create a java class and i'll create a person entity here okay so a simple class is created now let's add the properties so what i'll do i will add properties private string person id private string first name private string last name private integer age private list stuff string as hobbies okay and what i can do i can add one more list as an address person may have multiple addresses okay so i'll just add private list of address class and addresses so what i'll do this is the address class so let me go ahead and create one address collection so i'll just create address collection here and in the address i will just define private string address 1 private string address to private string city okay so these are the three fields that i'm adding in my address now what i need i need i get a setters and constructors and everything so what i'll do i'll use lumbar to create the all the boilerplate code using the other data annotation and i'll also use the red builder annotation to have the builder pattern implemented okay now i'll go to the person class here as well i'll do the same thing i'll use the data annotation to create all the boilerplate code and also i'll use the builder pattern from the lumbar itself now what i'll do i need to make sure that this particular person entity that i created is an entity or is a document representation for our mongodb so for that i need to use the address document annotation and this other document annotation is from the wagespringframework.data.mongodb okay and here within this i need to define the collection name so i'll define collection name equals to person so this is a person defined here then what i'll do i'll just do json include and i will just add includes dot non-empty sorry i will just add non-null better than non-empty okay so what are the fields are non-null that will be only stored in our mongodb so other fields won't be included and other than that i need to add my primary key okay so this is this will be considered as the id a unique id for my collection that will be my person id so yeah you can see that this is a simple entity or a collection that we have created that will interact with our mongodb okay now what we will do is we will create a repository that will interact with our mongodb for all the crud operations whatever operations we want to do for our mongodb using our springboard the repository will come into picture so let me go ahead and create the repository so i'll just create a class that says person repo sittery and this will be the interface okay and this will extends repository okay whenever we are working with the mysql that is relational database we were using the jpa repository but within the we will be using the repository and here we will also define what is the type of the repository or what is the type of the entity the type is person and what is the id type that is of type string okay and i will annotate this as repository you can see that it's very simple we just created the person repository that extends the repository and there we have given the type like this particular repository is of type person and the id is of type string now similarly let me just go ahead and create the services so we'll go ahead and create the services here i'll just define the person service that is the interface and we'll go ahead and define the person service impl that is the implementation for the person service so this person service impl will implement person service and this will annotate with service so this is our service layer and now what we will do we will create a controller so let me go ahead and create a controller in the controller package and here we will define this is a person controller okay and here i will define erderit rest controller and define request mapping slash person so you can see that we just created all the controller layer repository layer service layer and our collections now let's create the rest api that will allow us to store a person in our mongodb database so you're in the controller layer we need a object of a service so let's create the object and autovariate so i'll just define private person service and the reference to it and i will just do at the rate auto wire so we will get the object of person service now let's create the method so i'll just define public string save at the red request body i'll just pass in a person as the entire object okay so this is my entire object that i am going to pass from the rest api and this will be my post mapping okay we will be doing the post request here and what here i'll do i will just do return person service dot save and here i will just pass on person object now this particular method is still not available so what we have to do is we have to go ahead and create a method in our person service so the method is created now i have to implement this method as well so i'll go here i'll click on this one implementation and in this person service impl i will implement this method simple right so within this person service impl i will need the object of the repository because from the service layer from my business layer i need to connect to my database layer that is my mongodb database so for that i have created a repository and using that i will just save the database so i here i will just define person repository and i will auto wire it simple right and here what i'll do i will just define person repository dot cu i'll pass the entire person dot get person id and the method is completed so here you can see that it's completely similar to what you were doing in your gpa repository very simple whatever the code you were doing there the same code we did but the implementation is different here we are using the repository and we just provided the configuration for our mongodb rest everything is same so here you can see that how easy it is to work with mongodb using the springboard application now what we can do is we can test our application but before that let's go ahead and implement the api documentation so with the api documentation we can get all the documentation very easily and we can test our application easily so let's go ahead and implement it so for that we are going to implement the springfox swagger2 so we'll go to our palm.xml file here within the dependency section we will add the dependency so let me go ahead and add the dependency and here i'll just add springfox bootstarter it's from the group io.springfox and the version is added and then let me just go ahead and add another dependency for spring fox swagger ui and it's also from the io dot spring fox and the version is added now what i have to do is i have to go to my springboot mongodb application and i need to enable the swagger so i'll just define enable swagger2 okay now one more thing i need to do is i need to add the configuration for my spring and matches so let me go ahead and do that okay so this is the configuration that we need to add that is the spring mvc path match dot matching strategy equals to and path matches now once you do this we need to add a configuration for spring fox so we will create one package for config and within the config package we will create one class and we'll define springfox config okay and here we will add er the rate configuration and we'll create a docket bin so let me just create a bean and i'll just define public docket api return new and there is the documentation type.swagger2 dot select dot apis request handler selectors dot any so any request handler will be added and we'll also add the paths any path selectors will be added okay and dot build so you can see that it's very simple code okay so you can see that what we are doing is all the apis which are there in our application will be exposed in our documentation and we can go through from there so you can see it's simple added now let's start our application and let's see that first whatever the api that we created in our controller that is person controller post mapping to save the person is working or not so we will just start our application so you can see that my application is started and my application is also connected to my mongodb database now what we can do is we can go to the browser and we'll go to localhost port 8080 and slash swagger hyphen ui you can see that this is the ui to open your swagger so you can see that your application is started application is working and you can see your one controller is also added here that is person controller so let's go ahead and test this so you can see that we have one post api that we have added here right this is the post api so let's go ahead and try it we'll click on try it out and you can see that this is the type of json format it is expecting so let's give all the information so in the address i'll give as bangalore in the address to also i'll give bangalore cds bangalore ages 25 first name as shabbir last name s dowdy and i'll give the person ideas one two and the hobbies i'll give as ebc these are the simple data i am just passing okay now let's execute and you can see that i am getting my response body back that is 12 that is my personal id now if i go to my studio 3d my mongodb okay if i refresh okay you can see that demo database is created so this is a demo that we have defined in our springboot application in our configuration right you can see that the database is demo so within the database demo our collection should be created so here you can see that the person collection is created and you can see there is one record inserted so this is how you can see that the data is getting created now let's go ahead and build the other apis so we'll go to our springboard application we'll go to the controller back person controller and let's add other apis so now let's add api to find a person based on the given name so whatever the first name that i'll give based on based on that it will search a person and it will return a person okay so that's a simple api that we are going to create now so what i'll do i'll just public list of person i need okay because if i will pass up there and if there are multiple shop base then i'll need all those person okay so that's why i'm taking the list of person and i'll give get person start with and here i will pass one of the value and here this is the request param okay so request param i'll take as name string name and here what i'll do i'll just do return person service dot get person with person start with and here i'll pass the name okay a simple method that i'm going to create now this method is still not available within the person service so we need to go ahead and create it so let's go ahead and create a method there so create a method person start with in person service and you can see that the method is created now we need to implement that this method so we'll go to the implementation that is the person service inpl and here we will go ahead and implement the method so let's implement it so you can see that this method is very custom so this method won't be defaultly available within the repository so we need to define that method we need we need to give the declaration so after that the declaration will be able to use it so let's go ahead and declare the method so we'll go to the person repository and here we'll declare the method so here we'll define list of person and what we can do here find by what we need to find find by first name right so find by first name and starts with so we'll give starts with so what it will do is it will find all the person by first name starting with the given string so we'll pass string as name simple we just declare the method here and the implementation is by default by the repository now so this is something that we have to call from our service mpl so we'll call person repository dot find by first name start with and then we need to pass the name you can see that how simple it is to implement your all the different methods now let's test this method so what we'll do we will just restart our application and our application is restarted we'll go to our browser and we'll refresh our page and you can see that there is now two apis one that is person get person start with and the other one is save so within the database we have already stored one user that it should be right so let's try to search that so i'll just pass submit here and you can see that there is no data because shabiro's capital now you can see that i am getting data right so you can see that whenever there is no data we won't be able to get any data but if it matches we will get the all the records here so this way you can see that this particular api is also working completely fine and the url is this way localhost id slash person question mark name equals to shabir as this is the request parameter okay now let's go ahead and implement another api so now let's implement the delete api so here what we will do is we will implement delete so i'll just define public void delete and here okay sorry this is not something that we need to define here i'll just remove from here and i have to go to my controller right so here i have to add okay so this is the delete api and here i will just mention at delete mapping okay as this is the delete so a delete method will be called here and i will just pass the id so here i'll define this is the path variable and this is string id okay this is simple you can see that we are just defining the delete and what we will do we will call the person service dot delete we will just define the delete method here and we are going to pass the id okay simple now this delete method is still not available so what we will do is we will go ahead and create this method so let's go ahead and create a method so you can see that the method is created in the person service now we have to go to the implementation and add the implementation for it so within this service impl there is person service mpl we have to implement a method so let's go ahead and implement and what we will do using the person service itself person repository sorry we'll do delete by id [Music] okay and we'll pass the id and you can see how easy it is to implement the delete as well so the delete operation is also now implemented now let's implement another api now within this api what we will do is we will try to use the query annotation so using the query annotation we are trying to get the data now so what we'll do is we will create an api so that api will give all the person based on the age so we will define minimum age and maximum age so based on that mean age in max h it will give all the result and we are going to implement this using the address query annotation so let's go ahead and do that so we will go to our controller to implement our api so this is a person controller so let's go ahead and implement okay so we will define public list of person because we'll get list of person here okay and we will tell get by person age okay and we will define the get mapping and we will define slash age so the api would be slash person slash age and here we are going to pass the parameters so let's go ahead and do that so we will pass request param integer mean age and at the rate request param integer max age okay so these are the two fields that i am getting mean agent max max's based on this we need to find the data using at the rate query annotation so let's call our api so let's call our service so we'll just do it earn person service dot get by person age and we are going to pass mean age and maxage okay now this method is not still available within the person service so we need to add this method so we'll just create a method in the person service and we need to implement this method so we'll go ahead and implement this method here now you can see that the method is implemented now we need to use our repository layer to get our data so let's go to the person repository and implement the method so ideally what you can do is you can create a method that is list of person and you can give the method name that is find by age and you can pass between okay and here you can pass integer min and integer max okay so this is the default implementation you can give and you will get the data based on min and max's but this is using the repository but we need to see using the query annotation right so let's go ahead and do using the query annotation so i'll just keep it here this way so you can go ahead and use this but let's go ahead and do with query notation so here let me just create a method that is list of person written type and and i'll just define name file person by age between okay you can see that i've just given the different name here and i'm going to pass integer mean and integer max and now here i will use the query annotation so you can see that this query is from or springframework.data.mongodb okay and within the query region we need to pass the value so what value it is we need to pass the value using the curly braces we need to do the based on the age okay so we'll use age here as the property and we'll do colon and then we need to use again braces dollar gt with question mark 0 okay that means the age should be greater than the first parameter that is the minimum value that we have passed and dollar less than first parameter okay and this everything would be within the codes here so you can see that this is a simple query that i have defined and if you go here you can see that you will get all the properties as well here if i just remove this you can see all this methods are there that is less than greater than and equal operator greater than equal to in less than equal to not equal to okay not nor all these particular operations are there you can use any of the operations so here i'm just using greater than so i'm just defining that i need a query that is and the value should be i need to do the filtration that is i need data based on the age so age is the property within the person right is is the property within the person so with this age i need the data that is greater than the first parameter question mark zero is the first parameter okay so greater than the first parameter and less than the second parameter that is the question mark one okay this is equal to the data we are getting here and now what we will do is we will call this method so let's go ahead and go to the service impl and we will call this method now we will call return person repository dot find person by age between and here will pass manage and max each cool right you can see that how simple it was so let's go ahead and rerun the application and test this by that time let's go ahead and see the database that what was the age that we added that was 25 okay and my application is started let's go to the browser let's refresh the page and you can see that we should get the another api that is this is first api right get person start with this is the one get by personage you can see that dvd also is coming here but we need to use this so let's use this and let's test this out so i'll just try it out and here i need to give the min and max so max i'll give as 26 and the mean i'll give us 15 okay and i will execute and you can see that i am getting the data here cool right you can see that how easy it is if i just change the values right i will just add 24 here and if i execute you can see that you won't be getting any data now one more thing we can do here is suppose when you're getting the data what you need is you don't need any particular field you just need person id first name last name age and all those only okay you don't need particularly address here so that also you can define within your address query parameters so let's go ahead and do that what you can do is you can go here within the right query annotation to the person repository right so within this square annotation you can define fields okay when within these fields you can define which fields you need okay so suppose what i'm defining is the field that is addresses addresses so you make sure that the spanning is correct so i'll just copy from here ctrl c and i'll go to the repository and i'll define addresses and that is zero zero means i don't need one means i need whatever you want you can define so the only thing i defined is here that i don't need addresses field that means rest of the fields i'll get okay so let's go ahead and rerun the application so if i rerun this application started and if i go to my browser you can see that earlier for the same api i was getting the addresses okay now if i execute again you can see that i won't get the addresses i will only get my personal details cool right so this way you can filter out the data as well like which particular fields you need which particular fields you don't need you can exclude them as well okay now let's implement another api where we will implement a generic search so we'll create a search api and we'll pass all the different fields if the fields are available then we will be able to search otherwise we won't be able to search so that's the search api that we are going to build so let's go ahead to our spring booth that is intellij idea and let's go to the person controller and let's create one more api now within the search api what we are trying to do is we will implement a pagination as well so we will define a pagination and based on the page number and the page length will get the data and we will also do quite differently right rather than using the repository we are going to now use the template so you will get the understanding of both how to work with template as well and how to work with the repository as well till now we saw that we were working with the repository now we are going to implement the paging nation with search using the mango template mohawk template is also a part of the spring boot dependency so let's go ahead and do that let's implement public method that is the api and we will use the pagination so here we'll use page and this pages will be of type person and this is the search api okay search person and we will just annotate with get mapping and we'll just define slash search so slash person slash search is our api now let's add the request params so we will be adding different request params and whatever the request params would be available based on that we will add the search so we'll just define request param string name okay but what i will do is i will make sure that this request params are not mandatory so if i don't provide request params i need to get all the records but if i provide any filtration i need to get the records based on that okay so i'll just make sure that this required is false and then i'll just add again request param i'll just make sure that the required is false and i'll just mention integer mean age the same way i'll just do for the request param required is false integer okay again request param required is false string city so you can see that these are all the fields available in our person entity right so this all based on all those fields we are trying to implement a search and then after this let's add the page generation also so what i'll do i will just do request param default value equals to 0 integer page at the red request mapping value equals to phi and integer size the size of the page okay now let's create the pageable object page of equals to page request dot off and here you can see that within this we need to pass the page and the size so here i'll just pass the page and the size and here after this i'll just do return person service dot search and here i'll pass all the fields that is name mean age max age city and the pageable object so you can see that it's simple right we just define the search method here with all this particular fields so let's go ahead and create this method in our service okay so you can see that the method is created within the person service and now we need to implement this so let's go ahead and implement this method we'll implement this coal now as earlier i told you that we are going to implement this using the template right so we need to have the object of a template so let's define the object so i'll define in the starting that this is a template okay and i'll just auto wire that object simple okay we have not done anything yet now let's go ahead and implement this search method so what we will do is ideally whatever the fields are non-empty okay means whatever the values are there then only we will try to add this search otherwise we will just ignore it so we are going to create a criteria and we are going to add all those particular things in our criteria and based on that criteria we are going to fetch the results so let's do that so here let's define a query object and make sure that that query is off from the core query okay you can see that this is from the spring framework dot data dot mongodb dot co dot query not from the repository okay so the query is there query equals to new query dot with cageable okay so this query will be created using the pageable that we have defined now we need to define the list of criteria so we'll just define the list of criteria here equals to new era list now we need to define all these criterias now so the first thing is we'll work with the name so if name is not null and not blank then we need to add that particular thing in the criteria so simple if name is not equal to null and name is empty that means not empty right it's not empty then we need to add in the criteria so we'll just add in the criteria that is criteria dot add and we'll just define criteria dot where okay and here i'll just define the key key is first name because if you go to the person right the key is first name so this is the key that we need to provide okay dot rejects okay and here we are going to pass name okay the reject should be whatever the value that the name is passed that should be and it should be in case sensitive okay simple you can see that we just added one criteria so whenever the name is not null and the name is not blank at that time we are adding the criteria that we need all the data where its first name should match with the name that we have provided and it should be in case sensitive okay now let's work with min and max age so let's go here and work that if min is not equals to null and max age not equals to null then we need to work with this okay so here again we will add the criteria criteria criteria dot add criteria dot where and this field this key we need to pass that is the age because we are working with the edge if we go again with the person i mean and max age that we are working that is with the key age okay so we are using the age gear dot greater than okay so gt it should be greater than equals to the min age and less than lte and less than equal to the max age so you can see that we added the another criteria that when the manage and max's are not null then add the criteria where age should be greater than equal to minimum age and less than equal to maximum age now let's work with the cd so if ct is not equals to null and not of city dot is empty right then criteria dot add criteria dot where now you can see that we have to pass a key but city right city is inside where city is inside person but inside person's addresses right so person addresses dot city okay so inside the addresses there is a city right so that should be is is means equal equals to cd that we are passing simple right you can see that we added three criterias based on the conditions and we use multiple things we use regex is equal to and greater than less than equal to so this way whatever you need you can add the conditions within the criteria and you can create the criteria object cool right now once this criteria is done okay we need to add or we need to attach this criteria to our query so let's do that if criteria dot is empty okay not empty okay when the credit is not empty then we need to add so we will just add query dot add criteria and here we'll just new criteria dot and operator what we are doing is we are adding all this criteria using the and operator okay and we are doing this criteria dot two array new criteria of zero you can see that it's simple what we are doing is we created the list of criteria here we added all the criteria in a list like whenever uh the values are not null we are adding into the criteria at the end if criteria is not empty like uh anywhere the criteria is added what we are doing is at the end we are attaching that criteria to our query okay and within this add criteria there is a new criteria and and operator and this end operator takes the variable argument as array so we are converting this our list of criteria to the array of criteria that's it very simple okay nothing complex here it's converting from the list to array now once this is done now we are going to use the template to fetch the data in the pagination format so here what we'll do we will define page of person people equals to page of person people equals to page exit pageable execution utils okay dot get pagey now here within the get page you can see that what you have to pass you have to pass the content you have to pass the pageable and then you need to find the supplier as well like what is the total value for that particular list okay so let's go ahead and do that so here we'll define mocha template dot find and here i'll pass the query and what is the entity class that is person.class right so we'll define person dot class then we'll going to pass pageable then we need to pass the supplier supplier for the total list so here we'll pass template dot count will pass the query dot skip 0 dot limit 0 comma person dot class so you can see that we just added the entire page execution detail and then at the end we need to pass the people back so let's go it again so here you can see that we had to pass the three fields that is the entire list itself so from the first right from the mango template dot find from here we are going to get the entire list so mongodb.find we pass the query and we need person.class so here we will get the entire list of person and then we pass the pageable like what type of data we need and then we pass this supplier that is to get the count so here we pass template dot count and we got the entire account based on the query so once this is done the implementation is done now you can see that it's very simple implementation but looks complex but instead of using the repository we use the manga template here so let's go ahead and rerun our application you can see that the application started let's go to a browser and let's refresh the page and you can see that this is the search implemented here and you can see that these are all the different parameters so let's try it out so if we directly execute we should be able to get all the records right you can see that we are getting the records and there is a pageable as well so it will have all the list of data different data available so when you have a lot of data here you will be able to search it easily but here if i pass any other details right like suppose city is abc okay and if i try to execute you can see that you won't be getting any data right there is no data available so you can see that our search is working completely fine you can see that we implemented a search using all the different parameters if you don't pass any details you will get all the records but if you want to filter out the content you can add the filters here using the request parameters and you will get the data accordingly now let's go one step further now let's try to see the aggregation how aggregation works in mongodb and how we can implement aggregation and we can fetch data so let's try to implement an api in which api we will get the oldest person living in a particular city as you can see that we are adding all the persons right so what we'll do is a person will have an address and that address will have a city so what we are trying to do is we are trying to group all those data based on the city we are going to sort those data and we are going to find a person who is oldest in a particular city and we are going to bring all the data back suppose if i have 10 cities i will send that list of 10 cities and which particular person is the oldest in that city so that's the thing that we are going to implement here so let's go ahead and do that okay so i will go to my intellij idea and let's go to the controller and let's implement this so let's create a new api here i'll just define public list of document and you can see that we are going to use document from the rgot bson because mongodb stores the data in the binary json format okay so we are going to use that and we are just define get oldest person okay and this is the list here and this is going to be get mapping and the epa would be slash oldest person okay so slash person slash oldest person is going to be the api and here i'll just try to do return person service dot get oldest person by city okay so you can see that it's very simple here that old sp should be capital okay so you can see that i'm just implementing a simple api here where the oldest person in the city we are going to return back so let's implement this method in the service layer so let's create a method here and we need to implement this method so let's go to the implementation class and implement this method and here as well we are going to use the manga template and we are going to use the aggregation functions okay how the aggregation would work in the mongodb so let's see that so now here you can see that what i need is i need the oldest person by city now what i want is i from here now i need to access the cities now cities are inside the addresses and addresses are part of the cities so what i need to do is i need to flatten out that addresses okay so rather than having the list of addresses inside my person what i need is i need to flatten out that so i can directly access the addresses so it's called an unwind operation so i'm going to do an unwind operation on the addresses so directly i can access addresses from the person itself then what i'm going to do is after that i am going to sort all the data based on the age once the sorting is done i will group all the data based on the city so once that is done i will get the oldest person by cd okay so that's what i'm trying to do here so let's go ahead and do all those operations so we'll do unwind operation then we'll do sort operation and then we'll do group operation so we will define all these operations and we will pass all these operations in our aggregations and we are trying to get the data so let's implement this so first we'll define unwind operation okay unwind operation equals to aggregation dot unwind okay now where you need to do the unwind operation i want to do the unwind operation on addresses because we have a list of addresses that i need to unwind so it's directly accessible so if i go to the person this is the addresses so i'll just take this go to the person service impl and i'll pass addresses then i need to do this sorting operation so let's define that so i'll just define sort operation sort operation equals to aggregation dot sort i'll define sort dot direction is in descending order and then on what i want to do the sorting i want to do sorting on age okay so this is what something i define now i need to do the group operation so i'll just define group operation equals to aggregation dot group and here i need to group based on city city is inside addresses right so i need to take the addresses dot city okay then what i need to do is once i do that i need to take the first out of it because we have already done the sorting in the reverse order so once we have done the sorting in the reverse order i need to just take the first route so i just defined first and i need to do i need to get the document root and define aggregation dot root and how i want to store it so i'll define as i want to define as as the oldest person oldest person so you can see that this is something that i have added as a group i want to group based on the addresses.cd and once the once the group is done i need to get the document root okay and then i am saving everything in the oldest person that's something that i define in the group operation now let's do the aggregation so let's define aggregation equals to aggregation dot new aggregation and here you can see that this will take the varax of the operations so we will we can pass all the operations that we need to perform so i need to first perform unwind operation then sort operation then group operations okay simple thing now i need to get those data so i need to get list of as a document that is a person equals to i need to do template dot aggregate i need to pass the aggregation then i need to pass the input type input type is person.class and what i what is the output i need in the document so that is document.class okay then dot get mapped results so once that is done i can pass on the person back so you can see that it is simple okay let's try to go through again so what we did is we want to get the oldest person so the oldest person by the city the access to the city we can only get by the addresses so first we need to flatten the operation so that means we flatten out the addresses that means the unwrapped operation we did after that we need to sort the data so we sorted the data based on the age once that is done we group the data based on the city and we took the first document out of it and we need to do the aggregation so these are the three operations that we are going to do and wrap operation sort operation group operation we pass all the operations in the aggregation and that aggregation we passed on to our template to get the document back simple as it is okay you can see that everything is straightforward unwind sort group we pass everything to the aggregation that aggregation we pass to a mongodb to get the data back okay now let's run the application and see you can see that the application started let's go here to the browser let's refresh the page and here you can see that we got the data that is the get oldest person okay and let's try it out and let's execute so here you can see that in the bangalore okay in the city bangalore we are getting the oldest person ashabir because we have only added one record okay and within that one record within that city we have only one person that is the oldest one so this way the aggregation will happen and this way you will get the data back if you have multiple records you will get the data better so if you want to try out try adding multiple records and you will get the result back let's take one more example because this is still not enough to understand completely and to understand how the aggregation and everything work so let's take one more example let's create one more api in which we will try to do or we will try to get the population of the cities so if we have multiple cities available right so we'll try to get the population of it how much population we have for a particular city so that's the aggregation where that we are going to do so let's go ahead and implement it we will go to our intelligent idea let's go to our controller that is the person controller okay and let's implement a new api so we will implement public list of document get population by city and we will do get mapping here and we will define population by city okay and we are going to call this service layer from here so we are going to call person service dot get population by city cool right you can see that the simple method is declared here let's go ahead and declare the same method in our service layer so create a method get population by city in person service and let's undo it because we forgot to add the return statement right so let's go ahead and add the return statement okay and then let's add the method here create method and here the list of document is there now let's go ahead and implement this we'll go to the implementation and let's implement the method okay now here also we are going to do the same thing we have to do the aggregation operations so let's implement this okay so here we are going to do the same thing we are going to do the unwind operation that means we have to work with the cd so we are going to do the unwind operation once we unwind the operation we are going to do the grouping so we will group by cd and then we are going to sort it okay so the maximum one maximum population will come first so that's the plan so let's do all the operation so we'll do unwind operation here equals to aggregation dot unwind and we need to unwind based on the addresses so let me just copy addresses from here right so we are going to do unwind operation and then we are going to do the grouping operation so so we are going to group operation equals to aggregation dot group group based on what group based on city so that would be addresses dot city and then once that is done we need to count those and we need to store those okay so we will store in the population count cool right you can see that we aggregated it we grouped it and we added the count and we stored all the count in a pop count as a variable and then we need to do the sorting operation so let's do sorting so we will do sort operation equals to aggregation.sort and we need sort direction desc and we need to do sorting based on what based on the variable that we have declared here so we will define that based on this we need to do the sorting okay now we need to define the aggregation now with this aggregation we are going to add one more thing that is the projection like what data we need back we don't need all the data back right we i don't need an entire object i just need a particular fields out of it right so that's what we are going to implement using the projection here so let's do that so we are going to define the projection operation okay equals to aggregation.project dot and expression okay we are going to add all the expressions here so what i'm trying to do here is whatever my city is there right that city should come as id the pop count which i have write that pop count should come as count and actual id whatever is defined right that should not come okay my custom id should come and my population count as count should come so that's the simple thing that i'm going to add in the projection rest all the details i don't want it okay so that's what we are defining here in the add expression what i'm doing is whatever the id is there okay as i need the cd dot and expression whatever the pop count is there that i need as count dot and expression sorry what i need this is and expression and i need and exclude right this is not array sorry this should be only s and this is exclude so what i need to exclude is the underscore id okay so this is a simple projection that i've defined now we have to use this projection in our aggregation as well so let's do that aggregation aggregation equals to aggregation dot new aggregation so what i need to do here is first unwind operation then group operation then sort operation then projection operation simple okay so i just define all the operation which i need in the sequence then after that i need to pass this aggregation in your template to get the data so i need list of document as documents equals to mogo template dot aggregate i need to pass the aggregation then my input class that is person dot class and my output class that is the document dot class and dot get mapped results this is something that i want in back and return documents okay you can see that how simple it is right so we did unwind operation then group operation then sort operation then we did the projection as well that because we only need few of the details we pass everything in our aggregation and then we pass everything in our mango template so you can see that the entire method is completed now let's run the application again and let's see how it is working so you can see that my application started now let's go to the browser and let's refresh the page and my new get population by city api is here let's try it out okay and you can see that i am getting one city that is bangalore okay and the population count is one so let's try to add one more person and say check it out okay so what i'll do i will try to add ahmadabad okay ages 23 first name is vishwat the last name is and the person id is 2 3 okay and this it is m so let's try to execute this you can see that the data is saved here and now if i go ahead and try to get the population by city and if i execute it you can see that i am getting the population the bangalore is one and the bad is one okay and if i try to get the oldest person here okay that should also get me the same results that in the bangalore this is the oldest person okay and in the bar this is the oldest person so you can see that how easy it is to implement the aggregation as well in the mongodb using the spring boot so i hope you are enjoying this tutorial but we are still not over okay we still need to understand one more thing let's try to understand how the images are stored right so let's try to create the api and try to store the images so let's create a new controller and we will try to store images there so what we will do here now i will create one collection okay so let's create a new collection and i will say this is a photo okay simple okay here i will annotate with data to get all the boilerplate code and then i will add as a document now this is something that will create the collection so we need to define collection equals to photo okay and we'll define json include and i will just add include non-null okay now let's define the properties here so i'll define private string id private string title and private binary photo okay and this my id is my unique key right so i'll just define as the id so you can see that we just created the collection here as the entity here and now we need to work with this so for this let's create the repository so here we'll go and create the repository layer so let's define the class and define photo repository and this is going to be the interface and this is going to implement and this is going to extend sorry repository and this is of type photo and type string okay and we will define this as a repository you can see that the repository is also created now let's create the service layer so i'll just define the new services here photo service this is going to be the interface and we are going to create one more service that is photo service impl this is going to be the class and that is going to be implementing photo service cool right and this is going to be my service layer super cool now let's go ahead and create the controller layer you can see that how easy it is to create everything so let's go ahead and create the controller and we'll define photo controller okay and this is going to be my rest controller and we'll do request mapping as well that this is going to be my slash photo okay you can see that the controller is created the service layers are created and the repositories are also created now in this controller we need the access to the service layer so let's go ahead and do that so we'll just define private photo service photo service and we will auto wire it okay and here let's create the api to add the photo and retrieve the photo first let's try to add the photo so let's create the api here public string add photo okay and this is going to be the post mapping and this is going to be my request param and this request permit name as the image okay and what it's going to be multi-part file and as the image name okay you can see that it's very simple thing now within the springboard we need to define the configuration as well when we are working with the multi-part file like what's the size and everything that we can define or the application can able to upload or manage it so let's define all those configurations so i'll go to the application.properties here and i'll define the configuration simple that spring servlet multipart max file size is 256 mb the request can be of 256 mb and we are enabling the multipart in our request so that's the configuration that we need to add now let's go back to our controller and let's handle that so what we have to do here is we are taking the data here as a multi-part file in the name of an image so that we have to store so what i'll do i'll just define string id equals to photo service dot add photo and i'm going to pass the image here okay and i'm going to return id alongside image what i'm going to do is i'm going to pass the name as well so i'm going to pass image dot get original file name as well like what the file name was uploaded okay so that's a simple thing that i'm going to do now this add photo we need to implement we need to add another service layer so let's go ahead and add in our service layer so this is how we have added in the service layer and there is one implementation for this photo service so let's go ahead and implement in the photo service implement okay we have implemented now here in the photo service mpl we need the object of the repository so let's go ahead and create this so private photo repository and we need to auto wire it okay cool now here let's create the object of a photo so i'll create a photo equals to new photo and we will define everything photo dot sorry we are going to do the title here right so set title would be original file name and photo dot set photo equals to image dot get bytes and add exception in method signature okay yes now what i need to do is i need to create a new binary so for this i'll just create new binary and here i need to define the type so the type is bson binary type dot binary and here once the photo is created what i need to do is i need to do photo repository dot save photo dot get id okay so you can see that it's simple thing we just implemented the entire add photo implementation so whatever the photo is that it's going to be stored in the binary format in our mongodb so for this now let's create the api to download that photo as well based on the id that we provide so let's go to the photo controller again and let's implement a map api method here now here add photo we need to add the exception okay so we are not handling the exception for now that's easy to handle but i'm just showing you what are the things that we can do in the mongodb for the binaries as well so here let's implement the method public response entity and this response entities of type resource okay download photo that it get mapping okay we are going to pass the id based on the id we are going to get the data from the database mongodb and we are going to download this image so slash id okay and this is going to be your path variable string id now let's create the resource object equals to new byte array resource and then photo okay so before this we need to use the photo here right so let's take the photo object here photo photo equals to photo service dot get photo right based on the id provided so now let's implement this get photo method we'll go to the service layer and implement this method we'll go to the implementation and implement this method okay now based on this id what we'll do photo service photo repository dot find by id find by id and we're going to pass the id dot get okay because this will be the optional so we are using the get to get that once that is done we will go to our photo controller again we will get the photo here and here we are going to pass the photo dot get photo dot get data okay that's where your resource is ready now now we need to make sure that it is downloadable so we'll define return response ntt dot okay dot header http headers dot content disposition attachment what's the type of attachment right and here we'll give the file name equals to plus photo dot get title plus backward slash again and then this dot content type media type dot application octet stream okay dot body and in the body we need to pass the resource that's it you can see that how easy it is right we just get the photo here we created the resource object and in the response entity we pass the details here we pass how the header should be and how the content type should be now let's restart our application you can see that the application is restarted now let's go to the browser let's refresh the page and now you can see that we have the photo controller as well and within the photo controller we have two apis that is the post photo and get photo but now i will show you using the postman so let me just open the post menu and the api would be http localhost 8080 slash photo and it would be post mapping right so we will do your http localhost 80d slash photo it will be post mapping we will go to the parameters okay we will go to the body and it should be form data and the key should be image because you are taking the request parameter as the image so make sure that the key is image you type it out and here you will get the option to and here you select the file type rather than the text okay and then you will get the select option so select the file here i'm just selecting any file and i'm just doing the send and here you can see that the send operation happened here okay and the data is stored we got the id as well so if i go ahead in the studio 3t if i refresh my demo here let me just refresh all and you can see that the photo is added here and you can see that the data is added in the binary format in the photo as well okay so if i go to the postman again if i do slash photo slash id and if i change it to get then i should get my photo back okay now you can see that i'm not able to get it here but if i do the same thing here in the ui if i go to photo id if i try it out if i give my id here and execute you can see that i'll get a link to download so once i click on this i'll be able to download my file okay so you can see that how easy it is to implement anything in the mongodb you can see that how easy it was to implement the file handling as well so this is how easy it is to work with spring boot and mongodb so make sure that you explore all the things we covered a lot of things as well like how to completely do the crud operations how to handle the aggregations as well how to work with the mango template how to work with the repository layer as well and how to handle and how to work with the binary files as well so i will also make sure that this entire project is available in the git repository and i will add the link as well in the description below so you can easily check it out if you have any doubts regarding any of the things that we have covered then do let me know in the comment section below i will try to resolve the queries as soon as possible and if you like this video give us a thumbs up and subscribe to my channel for the upcoming videos also click on the join button to join my channel and support me and you can also click on the thanks button to donate as well so that's been it in this video i will see you in the next video till then happy coding bye
Info
Channel: Daily Code Buffer
Views: 23,885
Rating: undefined out of 5
Keywords: spring boot with mongodb, how to connect spring boot with mongodb, mongodb with spring boot, how to use mongodb with spring boot, mongodb, java, spring, spring with mongodb, springboot with mongo tutorial, spring boot mongodb, spring boot, mongodb tutorial, spring boot with mongodb crud example maven, dailycodebuffer
Id: vl6DstgPoW8
Channel Id: undefined
Length: 77min 23sec (4643 seconds)
Published: Wed Jul 27 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.