Projections using MongoDB Query in Spring Boot

Projections using MongoDB Query in Spring Boot | By default, the custom query fetches all variables/key data from the collection. But using Projections we can fetch only selected variables/keys from the collection. @Query(value="{ … condition…}", fields =" {…variable : 1.. }"

Here field section is used to select variables for display:-

  • One(:1) means display variable.
  • Zero(:0) means do not display variables.

Default values for display:-

  • Primary Key Variable => default is 1
  • Other variables => default is 0

Create a spring starter project with dependencies:- Lombok, Spring Data MongoDB.

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
@Data
@NoArgsConstructor
@AllArgsConstructor
@Document
public class Book {
    @Id
    private Integer bookId;
    private String bookName;
    private String bookAuthor;
    private Double bookCost;
    private String bookType;
}
public interface BookRepository extends MongoRepository<Book, String> { }
@Component
@Order(1)
public class MyDataRunner implements CommandLineRunner {

    @Autowired
    private BookRepository bookRepository;

    @Override
    public void run(String... args) throws Exception {
        bookRepository.deleteAll();

        bookRepository.save(new Book(2505, "Spring Boot", "A", 500.0, "BackEnd"));
        bookRepository.save(new Book(2506, "Microservice", "B", 600.0, "BackEnd"));
        bookRepository.save(new Book(2507, "Angular", "C", 700.0, "FrontEnd"));
    }

}

Spring Boot MongoDB Projections Example

// SQL: select bookName, bookAuthor from book where bid>?
@Query(value = "{bookId : {$gt : ?0}}", fields = "{bookName: 1, bookAuthor:1}")
List<Book> getAllBooksByIdProjections(Integer id);
repo.getAllBooksByIdProjections(100).forEach(System.out::println);

Output:-

We have used List as the return type therefore the unavailable fields like bookCost, and bookType are null. We can also use JSON string for the return type.

@Query(value = "{bookId : {$gt : ?0}}", fields = "{bookName: 1, bookAuthor:1}")
List<String> getAllBooksByIdProjections(Integer id);

Output:-

Output (Return Type of method) Custom Query for Project is only two Types:-

  • String
  • ClassType

Example: List, String, List, and Book are allowed.
Here, Object[ ], Double, etc are not allowed.

package com.knowprogram.demo.repo;

import java.util.List;

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

import com.knowprogram.demo.model.Book;

public interface BookRepository extends MongoRepository<Book, String> {
    // SQL: select * from book where bid>?
    @Query("{bookId : {$gt : ?0}}")
    List<Book> getAllBooksById(Integer id);

    // SQL: select bookName, bookAuthor from book where bid>?
    @Query(value = "{bookId : {$gt : ?0}}", fields = "{bookName: 1, bookAuthor:1}")
    List<String> getAllBooksByIdProjections(Integer id);

    // SQL: select bookAuthor fom book where bookType=?
    @Query(value = "{bookType: ?0}", fields = "{bookAuthor:1, _id:0}")
    List<String> getBooksDataA(String bookType);

    // SQL: select bookName, bookAuthor from book where bookName like ?
    @Query(value = "{bookName: {$regex: ?0}}", fields = "{bookName: 1, bookAuthor:1}")
    List<String> getBooksByBookName(String input);

    // SQL: select bookName, bookAuthor from book where bookId In (...)
    @Query(value = "{bookId: {$in: ?0}}", fields = "{bookName: 1, bookAuthor:1}")
    List<String> getBooksByBookIds(List<Integer> ids);

    // SQL: select bookName, bookAuthor from book where bookId In (...)
    @Query(value = "{bookId: {$gt: ?0, $lt: ?1}}", fields = "{bookName: 1, bookAuthor:1}")
    List<String> getBooksByBookIdBetween(Integer gt, Integer lt);

    // SQL: SELECT count(*) FROM BOOK WHERE bookId >?
    @Query(value = "{bookId: {$gt: ?0}}", count = true)
    Integer getBooksCount(Integer id);

    // SQL: SELECT * FROM BOOK WHERE bookId >? order by bookType
    // @Query(value = "{bookId: {$gt:?0}}", sort = "{bookType: 1}") // ascending
    // order
    @Query(value = "{bookId: {$gt:?0}}", sort = "{bookType: -1}") // descending order
    List<Book> getBooksInOrder(Integer id);

    @Query(value = "{bookId: {$gt:?0}}", delete = true)
    Long deleteBooksById(Integer id);
}
@Component
@Order(2)
public class DataTestRunner implements CommandLineRunner {

    @Autowired
    private BookRepository repo;

    @Override
    public void run(String... args) throws Exception {
        repo.getAllBooksByIdProjections(100)
            .forEach(System.out::println);

        repo.getBooksDataA("BackEnd")
            .forEach(System.out::println);

        // repo.getBooksByBookName("^S") // starts with ^<input>
        // repo.getBooksByBookName("e$") // ends with <input>$
        repo.getBooksByBookName("o") // containing
            .forEach(System.out::println);

        repo.getBooksByBookIds(Arrays.asList(2505, 2506))
            .forEach(System.out::println);
        
        repo.getBooksByBookIdBetween(2500, 2900)
            .forEach(System.out::println);

        System.out.println(repo.getBooksCount(2500)); // 3
        System.out.println(repo.getBooksInOrder(2500));
        System.out.println(repo.deleteBooksById(2500));
    }

}

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 *