Spring Boot with MongoDB Basic Example

Spring Boot with MongoDB Basic Example | Install the MongoDB database, and let us create a spring boot application to connect the MongoDB and perform some CRUD operations. For all CRUD operations see:- Spring Data JPA Introduction. Also see:- SQL v/s NoSQL Databases

MongoDB Commands

To start MongoDB Server (starts on port number: 27017):-
> mongod

To start MongoDB client:-
mongosh
Or,
mongo

MongoDB client commands

To see the current database:-
db

To view all databases:-
show dbs

To create(if not exist)/enter into Database:-
use <databaseName>

It creates a sample database only after creating at least one collection. Example:-
use sample

The collection is created when we insert data. In SQL dbs first, we create a table and then insert rows but in NoSQL inserting the row, will create a collection (if not exist) and insert the row.

To insert data:-
db.<collectioName>.insertOne({ k:v });

Example:-
db.student.insertOne({"sid":10,"sname":"A","sfee":3.2});

MongoDB generates one primary key field/key with a HexaDecimal value created with the name _id: ObjectId("__"). Here, _id behaves like the primary key.

To view all JSON Documents in the collection:-
db.<collectionName>.find();

Example:- db.student.find();

To view output in pretty print:-
db.student.find().pretty();

To view all collections that exist in the database:-
show collections

Pass conditions for data fetch (where condition):-

// SQL: select * from student where sid=11
> db.student.find({"sid":10}).pretty();

// SQL: select _id, sname from student where sid=11
> db.student.find({"sid":11},{"sname":1}).pretty();

To Delete one collection:-
db.student.drop();

To delete the current database:-
db.dropDatabase();

SymbolMongoDB Code
<{$lt : val}
<={$lte: val}
>{$gt: val}
>={$gte: val}
!={$ne : val)
// SQL: select * from student where sid>=10
db.student.find({"sid": {$gte:10}}).pretty();

// SQL: select * from student where sid!=10
db.student.find({"sid": {$ne:10}}).pretty();

To insert the data in MongoDB, three methods are there:- insert(), insertOne(), and insertMany(). The insertOne() is used to insert one record, insertMany() is used to insert multiple records at a time. The insert() method is deprecated but it can be used to insert either one or multiple records.

To insert multiple JSON Objects:-

db.student.insertMany([
   {"sid":202,"sname":"Rocco","sfee":400.2},
   {"sid":203,"sname":"Jerry","sfee":600.2},
   {"sid":204,"sname":"William","sfee":800.2}
]);

MongoDB

  • MongoDB is a NoSQL Database.
  • It stores Data in Collections(similar to tables).
  • Collections store data in JSON Format(Document)
  • Queries are called commands/functions.
  • Start MongoDB server mongod then start the Mongo client mongo or ‘mongosh.
  • It is an unstructured Database, with no fixed schema.
  • It supports easy scaling(both – Horizontal and Vertical).
  • MongoDB server runs on port: 27017 (default)
  • The primary Key type in MongoDB is String[must be], with variable name id, then only the database generates a Hexadecimal Value (UUID). If we modify the type from String to any other then MongoDB will not generate value, assign it manually.
  • @Id (org.springframework.data.annotation) Must be applied on any one variable. If we do not provide then the default variable is taken as id with default type String and MongoDB generates a hexadecimal value.
  • @Document annotation is optional. To provide collection details we can use it. If we do not provide a collection name, then the default is className (with lowercase).
  • TODO all Database operations in MongoDB, Spring Data API has provided one interface MongoRepository<T, ID>. Here:- T = Model class Name, ID = PrimaryKey DataType (ex: String). This interface internally extends two more CrudRepository and PagingAndSortingRepository.
  • Do not use JPA Annotations and concepts (like @Entity and show_sql, ddl-auto, dialect, etc). It is a NoSQL Database.

Spring Boot with MongoDB Basic Example

Create Spring Boot Project with the following dependencies:- lombok, Spring Data MongoDB.

If we add spring-boot-starter-data-mongodb (Spring Data MongoDB) dependency then our project behaves as client(MongoDB Client) then by default it create connection with details:- default port = 27017, host=localhost, database=test.

In application.properties:-

spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
# if given database not exist then auto-created
spring.data.mongodb.database=kp

#spring.data.mongodb.username=
#spring.data.mongodb.password=

In Mongodb ID will work as the primary key. It is auto-generated and hexa decimal value therefore in the Model class we have to use String data type for it.

package com.knowprogram.demo.model;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
@RequiredArgsConstructor
@Document(collection = "booksdata")
public class Book {

    @Id
    private String id;

    @NonNull
    private Integer bookId;

    @NonNull
    private String bookName;

    @NonNull
    private String bookAuthor;

    @NonNull
    private Double bookCost;
}

In @Document(collection = “booksdata”) passing the collection name is optional, if we don’t pass then the class name will be considered as the collection name.

@Id (is not from Data JPA) indicates the primary key variable. The variable name recommended is ‘id’ and the datatype is ‘String’.

Repository:-

package com.knowprogram.demo.repo;

import org.springframework.data.mongodb.repository.MongoRepository;

import com.knowprogram.demo.model.Book;

public interface BookRepository extends MongoRepository<Book, String> {

}

Runner class to insert and fetch the data:-

package com.knowprogram.demo.runner;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import com.knowprogram.demo.model.Book;
import com.knowprogram.demo.repo.BookRepository;

@Component
public class MyDataRunner implements CommandLineRunner {

    @Autowired
    private BookRepository bookRepository;

    @Override
    public void run(String... args) throws Exception {
        bookRepository.save(new Book(2505, "Spring Boot", "A", 500.0));
        bookRepository.save(new Book(2506, "Microservice", "B", 600.0));
        bookRepository.save(new Book(2507, "Angular", "C", 700.0));
        
        List<Book> bookList = bookRepository.findAll();
        System.out.println(bookList);
    }

}

In Mongodb client:-

> show dbs
> use kp
> show collections
booksdata
kp> db.booksdata.find().pretty()
[
  {
    _id: ObjectId('66821bb8b851d804e93637b8'),
    bookId: 2505,
    bookName: 'Spring Boot',
    bookAuthor: 'A',
    bookCost: 500,
    _class: 'com.knowprogram.demo.model.Book'
  },
  {
    _id: ObjectId('66821bb8b851d804e93637b9'),
    bookId: 2506,
    bookName: 'Microservice',
    bookAuthor: 'B',
    bookCost: 600,
    _class: 'com.knowprogram.demo.model.Book'
  },
  {
    _id: ObjectId('66821bb8b851d804e93637ba'),
    bookId: 2507,
    bookName: 'Angular',
    bookAuthor: 'C',
    bookCost: 700,
    _class: 'com.knowprogram.demo.model.Book'
  }
]

Which datatype can be used to create the Primary key variable in the Model class? String (even any other Primitive Type Integer, Char, Boolean).

How collection is created in MongoDB if there is no ddl-auto? When we perform insert function/commands, then the database creates a collection first if not exist next insert data.

If we provide the ID, then we can get the generated ID back to the Application, else we can not see ID.

@Id
private String id;

We can choose the non-string type for primary key variable creation, then:-

  • This time ID is not generated.
  • Variable name(bookId) is mapped with _id key in DB
@Id
private Integer bookId;
// valid or not
class Person {
    @Id
    Integer pid;
    String pname;
}
Valid, but id not generated. We need to provide.
// valid or not
class Person {
    Integer pid;
    String pname;
}
Valid, auto-generated id with String(hexadecimal)
// valid or not
class Person {
    @Id
    String id;
    Integer pid;
    String pname;
}
Valid, we can even see generated id at Application.

We can define manual code for the customization of ID.

package in.nareshit.raghu;
import java.util.Random;
public interface MyIdGen {
    public static int getId() {
        return new Random().nextInt(999999);
    }
}

Spring Data MongoDB Operations

  1. save(obj): This method is used to execute either INSERT or UPDATE (based on ID/PK). The given object is converted into JSON Format and stored in Collection (inside MongoDB Database).
  2. saveAll(Iterable<T> list): This is called bulk insert/update. We can provide a list of objects for insert/update.
  3. Optional<T> findById(id): This method is used to fetch one row of data if exists else null. Read data using the get() method after doing a null check using isEmpty(), isPresent() methods.
  4. List findAll(): This method is used to fetch all rows of data from DB Collection.
  5. Boolean existsById(ID): This method is used to find whether the given ID exists in the collection or not.
  6. List<T> findAllById(Iterable list): This method is used to fetch selected rows by id.
  7. void deleteById(id): This method is used to remove one JSON document by id.
  8. deleteAll(): This method is used to remove all JSON documents from the Collection.
  9. count(): Number of JSON documents from collection.
  1. Page findAll(Pageable<T>): This method is used to implement the pagination concept by providing input like Page number and Page size.
  2. List<T> findAll(Sort): This method is used to fetch data by sorting operations.

What are the defaults for MongoDB Connection using Spring Boot?
host = localhost
port = 27017
database = test
Comes with no Security concept i.e. username and password are null.

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *