17 Working with Spring Data MongoDB


This chapter covers

  • Introducing MongoDB
  • Examining Spring Data MongoDB
  • Working with a database using MongoRepository
  • Working with a database using MongoTemplate

Document-oriented databases are one of the types of NoSQL databases, keeping the information as a key-value store. MongoDB is such a database program. Spring Data MongoDB, as part of the larger Spring Data umbrella project, facilitates the interaction of Java programs with the MongoDB document database.

17.1 Introducing MongoDB

MongoDB is an open-source document-oriented NoSQL database. MongoDB uses JSON-like documents to keep the information. MongoDB uses the concepts of databases, collections, and documents.

A database represents a container for collections. After installing MongoDB, you will generally get a set of databases.

A collection is similar to tables in the world of RDBMSs (Relational Database Management Systems). A collection may contain a set of documents.

A document represents a set of key-value pairs, equivalent to rows in RDBMSs. Documents belonging to the same collection may have different sets of fields. Fields that are common in a collection may contain data of different types. These things are known as dynamic schemas.

Table 17.1 summarizes the terminology equivalences between relational databases and the NoSQL database MongoDB.

Table 17.1 Compared terminology, RDBMS vs MongoDB

Relational databases










17.2 Introducing Spring Data MongoDB

17.3 Using MongoRepository to access a database

17.3.1 Defining query methods with Spring Data MongoDB

17.3.2 Limiting query results, sorting, and paging

17.3.3 Streaming results

17.3.4 The @Query annotation

17.4 Query by Example

17.5 Referencing other MongoDB documents

17.6 Using MongoTemplate to access a database

17.6.1 Configuring the access to the database through MongoTemplate

17.6.2 Executing CRUD operations using MongoTemplate

17.7 Summary