How to enable logging MongoDB queries for Spring Boot applications

Hamza Sabljakovic
2 min readMay 18, 2022
MongoDB query logs

In the spring ecosystem, it’s straightforward to configure, enable or disable different features via externalized properties. Mongo Template is no exception and it’s simple as adding a one-liner to the application.properties file:

logging.level.org.springframework.data.mongodb.core.MongoTemplate=DEBUG

If however, you are using the reactive version of Mongo Template, the configuration is slightly different.

logging.level.org.springframework.data.mongodb.core.ReactiveMongoTemplate=DEBUG

Also, since String Data repositories are built on top of the Mongo Template, all queries generated by the repositories are logged automatically once the logging is enabled.
If we take the repository and entity from the previous blog post and run the following code:

@Bean
CommandLineRunner runner(final ProductsRepository productsRepository){
return args -> {
productsRepository.deleteAll();
productsRepository.insert(new Product("A new product"));
productsRepository.findAll();
productsRepository.count();
};
}

The output in the logs:

2022-05-17 20:15:03.115 DEBUG 36105 --- [ main] o.s.data.mongodb.core.MongoTemplate : Remove using query: {} in collection: product.2022-05-17 20:15:03.135 INFO 36105 --- [ main] org.mongodb.driver.connection : Opened connection [connectionId{localValue:3, serverValue:12}] to localhost:270172022-05-17 20:15:03.183 DEBUG 36105 --- [ main] o.s.data.mongodb.core.MongoTemplate : Inserting Document containing fields: [name, _class] in collection: product2022-05-17 20:15:03.210 DEBUG 36105 --- [ main] o.s.data.mongodb.core.MongoTemplate : find using query: {} fields: Document{{}} for class: class com.sabljakovic.mongospringdemo.Product in collection: product2022-05-17 20:15:03.235 DEBUG 36105 --- [ main] o.s.data.mongodb.core.MongoTemplate : Executing count: {} in collection: product

As we can see, the Mongo Template logger does not log the raw queries that we take and execute directly in the mongo shell. Still, this can be handy for debugging in certain situations.

--

--