Day04 of #100DaysofCode as #100DaysOfMongoDB
A little away from Aggregations today, will be sharing an example for a simple spring boot MVC architecture example, which tries to connect to MongoDB Atlas using a certificate(say X.509 Certificate)
The MongoDB Atlas provides the scope for deploying and managing the database to build global applications on major cloud providers.
Hence, creating a cluster over say AWS, and it will allow you to perform CRUD operations on the local application.
Here is a small example wherein I tried to insert data using a simple MVC based architecture which takes first and last name as input parameters and can be queried along the same line.
The steps used here to create a connection are:
-
The URI by which you are trying to connect to the MongoDB Atlas cluster should be in correct format as per the format.
If you look at the following Post where the ssl connection was not getting established.
If you look at the URI Format documentation for reference. -
Try to create a MVC project with Repository class, Model Class and Controller Class in order to do CRUD operations, Insert data and Query Data through the spring boot application:
Here is the sample code for the same:
> package com.springtest.demo.repo;
>
> import com.springtest.demo.models.User;
> import org.springframework.data.mongodb.repository.MongoRepository;
> import org.springframework.stereotype.Repository;
>
> @Repository
> public interface UserRepo extends MongoRepository<User, String> {
> }
Controller Class:
>
> ackage com.springtest.demo.controller;
>
> import com.springtest.demo.models.User;
> import com.springtest.demo.repo.UserRepo;
> import org.springframework.beans.factory.annotation.Autowired;
> import org.springframework.web.bind.annotation.GetMapping;
> import org.springframework.web.bind.annotation.RestController;
>
> import java.util.List;
>
> @RestController
> public class UserController {
>
> private final UserRepo userRepo;
>
> @Autowired
> public UserController(UserRepo userRepo){
> this.userRepo = userRepo;
> }
>
> @GetMapping("/users")
> public List<User> getUser(){
> return userRepo.findAll();
> }
>
> }
Attaching following logs from the connection and data being inserted:
com.springtest.demo.DemoApplication : Starting DemoApplication using Java 17.0.2 on Aasawaris-MacBook-Pro.local with PID 72205 (/Users/aasawari.sahasrabuddhe/Downloads/demo/target/classes started by aasawari.sahasrabuddhe in /Users/aasawari.sahasrabuddhe/Downloads/demo)
> 2022-03-08 15:17:05.679 INFO 72205 --- [ restartedMain] com.springtest.demo.DemoApplication : No active profile set, falling back to default profiles: default
> 2022-03-08 15:17:05.735 INFO 72205 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
> 2022-03-08 15:17:05.735 INFO 72205 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
> 2022-03-08 15:17:06.185 INFO 72205 --- [ restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data MongoDB repositories in DEFAULT mode.
> 2022-03-08 15:17:06.218 INFO 72205 --- [ restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 30 ms. Found 1 MongoDB repository interfaces.
> 2022-03-08 15:17:06.588 INFO 72205 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8093 (http)
> 2022-03-08 15:17:06.595 INFO 72205 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat]
> 2022-03-08 15:17:06.595 INFO 72205 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/10.0.16]
> 2022-03-08 15:17:06.632 INFO 72205 --- [ restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
> 2022-03-08 15:17:06.633 INFO 72205 --- [ restartedMain] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 897 ms
> 2022-03-08 15:17:06.861 INFO 72205 --- [ restartedMain] org.mongodb.driver.cluster : Cluster created with settings {hosts=[127.0.0.1:27017], srvHost=cluster0.jrhrm.mongodb.net, mode=MULTIPLE, requiredClusterType=REPLICA_SET, serverSelectionTimeout='30000 ms', requiredReplicaSetName='atlas-292w65-shard-0'}
> 2022-03-08 15:17:06.978 INFO 72205 --- [hrm.mongodb.net] org.mongodb.driver.cluster : Adding discovered server cluster0-shard-00-02.jrhrm.mongodb.net:27017 to client view of cluster
> 2022-03-08 15:17:07.011 INFO 72205 --- [hrm.mongodb.net] org.mongodb.driver.cluster : Adding discovered server cluster0-shard-00-00.jrhrm.mongodb.net:27017 to client view of cluster
> 2022-03-08 15:17:07.012 INFO 72205 --- [hrm.mongodb.net] org.mongodb.driver.cluster : Adding discovered server cluster0-shard-00-01.jrhrm.mongodb.net:27017 to client view of cluster
> 2022-03-08 15:17:07.174 INFO 72205 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729
> 2022-03-08 15:17:07.519 INFO 72205 --- [ngodb.net:27017] org.mongodb.driver.connection : Opened connection [connectionId{localValue:5, serverValue:26636}] to cluster0-shard-00-01.jrhrm.mongodb.net:27017
> 2022-03-08 15:17:07.519 INFO 72205 --- [ngodb.net:27017] org.mongodb.driver.connection : Opened connection [connectionId{localValue:6, serverValue:24652}] to cluster0-shard-00-02.jrhrm.mongodb.net:27017
> 2022-03-08 15:17:07.519 INFO 72205 --- [ngodb.net:27017] org.mongodb.driver.connection : Opened connection [connectionId{localValue:1, serverValue:24652}] to cluster0-shard-00-02.jrhrm.mongodb.net:27017
> 2022-03-08 15:17:07.519 INFO 72205 --- [ngodb.net:27017] org.mongodb.driver.connection : Opened connection [connectionId{localValue:3, serverValue:25610}] to cluster0-shard-00-00.jrhrm.mongodb.net:27017
> 2022-03-08 15:17:07.519 INFO 72205 --- [ngodb.net:27017] org.mongodb.driver.connection : Opened connection [connectionId{localValue:2, serverValue:25610}] to cluster0-shard-00-00.jrhrm.mongodb.net:27017
> 2022-03-08 15:17:07.519 INFO 72205 --- [ngodb.net:27017] org.mongodb.driver.connection : Opened connection [connectionId{localValue:4, serverValue:26520}] to cluster0-shard-00-01.jrhrm.mongodb.net:27017
> 2022-03-08 15:17:07.519 INFO 72205 --- [ngodb.net:27017] org.mongodb.driver.cluster : Monitor thread successfully connected to server with description ServerDescription{address=cluster0-shard-00-02.jrhrm.mongodb.net:27017, type=REPLICA_SET_SECONDARY, state=CONNECTED, ok=true, minWireVersion=0, maxWireVersion=13, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=183920181, setName='atlas-292w65-shard-0', canonicalAddress=cluster0-shard-00-02.jrhrm.mongodb.net:27017, hosts=[cluster0-shard-00-02.jrhrm.mongodb.net:27017, cluster0-shard-00-00.jrhrm.mongodb.net:27017, cluster0-shard-00-01.jrhrm.mongodb.net:27017], passives=[], arbiters=[], primary='cluster0-shard-00-01.jrhrm.mongodb.net:27017', tagSet=TagSet{[Tag{name='nodeType', value='ELECTABLE'}, Tag{name='provider', value='AWS'}, Tag{name='region', value='AP_SOUTH_1'}, Tag{name='workloadType', value='OPERATIONAL'}]}, electionId=null, setVersion=7, topologyVersion=TopologyVersion{processId=62263dc244611ef569db1e07, counter=3}, lastWriteDate=Tue Mar 08 15:17:07 IST 2022, lastUpdateTimeNanos=196121665163299}
> 2022-03-08 15:17:07.519 INFO 72205 --- [ngodb.net:27017] org.mongodb.driver.cluster : Monitor thread successfully connected to server with description ServerDescription{address=cluster0-shard-00-01.jrhrm.mongodb.net:27017, type=REPLICA_SET_PRIMARY, state=CONNECTED, ok=true, minWireVersion=0, maxWireVersion=13, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=206546822, setName='atlas-292w65-shard-0', canonicalAddress=cluster0-shard-00-01.jrhrm.mongodb.net:27017, hosts=[cluster0-shard-00-02.jrhrm.mongodb.net:27017, cluster0-shard-00-00.jrhrm.mongodb.net:27017, cluster0-shard-00-01.jrhrm.mongodb.net:27017], passives=[], arbiters=[], primary='cluster0-shard-00-01.jrhrm.mongodb.net:27017', tagSet=TagSet{[Tag{name='nodeType', value='ELECTABLE'}, Tag{name='provider', value='AWS'}, Tag{name='region', value='AP_SOUTH_1'}, Tag{name='workloadType', value='OPERATIONAL'}]}, electionId=7fffffff0000000000000089, setVersion=7, topologyVersion=TopologyVersion{processId=62263c95fc481516f34bd6f1, counter=6}, lastWriteDate=Tue Mar 08 15:17:07 IST 2022, lastUpdateTimeNanos=196121665168063}
> 2022-03-08 15:17:07.519 INFO 72205 --- [ngodb.net:27017] org.mongodb.driver.cluster : Monitor thread successfully connected to server with description ServerDescription{address=cluster0-shard-00-00.jrhrm.mongodb.net:27017, type=REPLICA_SET_SECONDARY, state=CONNECTED, ok=true, minWireVersion=0, maxWireVersion=13, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=261042452, setName='atlas-292w65-shard-0', canonicalAddress=cluster0-shard-00-00.jrhrm.mongodb.net:27017, hosts=[cluster0-shard-00-02.jrhrm.mongodb.net:27017, cluster0-shard-00-00.jrhrm.mongodb.net:27017, cluster0-shard-00-01.jrhrm.mongodb.net:27017], passives=[], arbiters=[], primary='cluster0-shard-00-01.jrhrm.mongodb.net:27017', tagSet=TagSet{[Tag{name='nodeType', value='ELECTABLE'}, Tag{name='provider', value='AWS'}, Tag{name='region', value='AP_SOUTH_1'}, Tag{name='workloadType', value='OPERATIONAL'}]}, electionId=null, setVersion=7, topologyVersion=TopologyVersion{processId=62263b5055c8d646e1c81237, counter=4}, lastWriteDate=Tue Mar 08 15:17:07 IST 2022, lastUpdateTimeNanos=196121665201937}
> 2022-03-08 15:17:07.521 INFO 72205 --- [ngodb.net:27017] org.mongodb.driver.cluster : Setting max election id to 7fffffff0000000000000089 from replica set primary cluster0-shard-00-01.jrhrm.mongodb.net:27017
> 2022-03-08 15:17:07.521 INFO 72205 --- [ngodb.net:27017] org.mongodb.driver.cluster : Setting max set version to 7 from replica set primary cluster0-shard-00-01.jrhrm.mongodb.net:27017
> 2022-03-08 15:17:07.521 INFO 72205 --- [ngodb.net:27017] org.mongodb.driver.cluster : Discovered replica set primary cluster0-shard-00-01.jrhrm.mongodb.net:27017
> 2022-03-08 15:17:07.557 INFO 72205 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8093 (http) with context path ''
> 2022-03-08 15:17:07.565 INFO 72205 --- [ restartedMain] com.springtest.demo.DemoApplication : Started DemoApplication in 2.143 seconds (JVM running for 2.532)
> 2022-03-08 15:17:07.829 INFO 72205 --- [ restartedMain] ConditionEvaluationReportLoggingListener :
User[id: '60rf4533789h7800gh5h', Aasawari', Sahasrabuddhe']
User[Id: '689bjhdg67u83be3e65r', 'Aniket', 'Sharma']
Important points to remember here are
- The URI and URI according to the version of the application language you are using for development.
- The addition of the Certificate in the code correctly so that correct access rights are provided.
- Performing the right CRUD operation which should be according to the access rights given to the project owner.
If you have any further questions , please do share your feedback.
Thanks
Aasawari
Share on twitter: https://twitter.com/Aasawari_24