SpringPortal #3 - MongoDB Atlas with Spring Boot

Using MongoDB Atlas connection in MongoDB

MongoDB

MongoDB is a NoSQL database that uses JSON-like documents to map and store data from Java objects.

Spring framework provides a very intuitive way that allows effortless operability between Spring and MongoDB.

Setting up Database in MongoDB Atlas

MongoDB Atlas allows creating a free database of size 512 MB to try the Atlas. You can learn more at MongoDB Free Database.

  1. Create a free account on the MongoDB atlas website.
  2. You'll see a similar screen:

    python-512.png

  3. Start a new project.
  4. You'll be asked for the project name and then the project owner. Select a name that you like and you can go with the default owner.
  5. Now, build a Database by clicking the "Build a Database" button and selecting the "Shared" cluster.
  6. You can now move forward with pretty much the other default values. I'm using the cluster name "SpringPortalCluster". image.png

Now, Atlas will start provisioning your free cluster. But, still steps are left,

  1. Create a username & password.
  2. Add your current IP to the Atlas using the "Add My Current IP Address" button, which will allow only the specified IP address to connect to the cluster. image.png
  3. Complete the setup and connect it using MongoDB Atlas.
  4. In MongoDB Atlas, create a database. image.png
  5. We'll use this database and collection to connect from Spring.

  • If you don't want to use MongoDB Atlas, you can also create a database locally.

Connecting MongoDB to Spring

  1. For connecting your Spring project to MongoDB, you need to have the following dependency in your pom.xml.

           <dependency>
               <groupId>org.springframework.boot</groupId>
               <artifactId>spring-boot-starter-data-mongodb</artifactId>
           </dependency>
    
  2. Add @EnableMongoRepositories annotation to your application class.

    @SpringBootApplication
    @EnableMongoRepositories
    public class HelloSpringApplication {
    
       public static void main(String[] args) {
           SpringApplication.run(HelloSpringApplication.class, args);
       }
    
    }
    
  3. Now, if you run the application, it'll try to connect to the MongoDB database but since we haven't told it the MongoDB connection string, it'll try localhost:27017 which you can use if want to try to run the MongoDB server locally.
  4. But, since we've already created an Atlas database we want to connect to it. We need to add an application.properties file to the project's resource directory if it is already not present there.
  5. Add the spring.data.mongodb.uri= property, Screenshot 2022-11-12 021841.png
  6. You should be able to see the successful connection to the MongoDB server in the logs.

Coding the MongoDB support

  1. For using MongoDB in your Spring application, you need to do the following steps:

    1. Declare a document class.
    2. Declare a MongoRepository interface.
  2. We'll add @Document annotation to our Person class:

    @Data
    @Builder
    @ToString
    @Document    // Identifies the object which needs to be stored in MongoDB.
    @NoArgsConstructor
    @AllArgsConstructor
    public class Person {
    
       @Id          // @Id annotation indicates the primary key of the document
       Long id;
    
       String firstName;
    
       String lastName;
    
       Date dob;
    }
    
  3. Add a package named repository.

  4. Add an interface that will extends MongoRepository,

     @Repository
     public interface PersonRepository extends MongoRepository<Person, Long> {
    
     }
    
    1. The Repository is marked with the Repository annotation which indicates that this interface supports CRUD operations.
    2. MongoRepository<Person, Long> takes two template parameters.
    3. Person defines the object type which will be used by Spring during JSON serialization and deserialization.
    4. Long indicates the type of ID that our object uses.
  5. If you run the application right now and there is no error, you will see a collection created in MongoDB with the name person.

  6. Now that we set up the repository, we can use it in the service method.

    @Service
    public class PersonService {
    
       @Autowired
       private PersonRepository personRepository;
    
       public Person addPerson(Person person) {
           if (person.getId() == null) {
             person.setId(RandomUtil.generateLongId(personRepository));
           }
    
           return personRepository.save(person);
       }
    
       public Person getPerson(long id) {
           return personRepository.findById(id).orElse(null);
       }
    }
    
    1. We're auto-wiring our repository.
    2. This repo object will allow us to do various CRUD operations in MongoDB.
  7. In the above service, we've also set the ID. Spring set the ID automatically if it is an Object or String type. But for numerical type, we need to set it explicitly.

  8. For generating the ID, we've created a method.

    public static long generateLongId(MongoRepository<?, Long> mongoRepository) {
       long id;
    
       do {
           id = Math.abs(new Random().nextLong());
       }
       while (id != 0 || mongoRepository.existsById(id));
    
       return id;
    }
    
  9. Now we just need to update our controller.

    @RestController
    @RequestMapping("/person")
    public class PersonApi {
    
       @Autowired
       PersonService personService;
    
       @PostMapping("/add")
       public ResponseEntity<Person> addPerson(@RequestBody Person person) {
           return ResponseEntity.ok(personService.addPerson(person));
       }
    
       @GetMapping("/get")
       public ResponseEntity<Person> getPerson(@RequestParam Long id) {
           Person requestPerson = personService.getPerson(id);
    
           if (requestPerson == null) {
               // this will return a 404 response.
               return ResponseEntity.notFound().build();
           }
    
           return ResponseEntity.ok(requestPerson);
       }
    }
    

Bringing it all together

  1. Adding a person

    image.png

  2. Getting the person

    image.png

  3. Entry can also be viewed in MongoDB compass:

    image.png


GitLab

Code Repository

Article-specific commit

Did you find this article valuable?

Support Naman Jain by becoming a sponsor. Any amount is appreciated!