|
| 1 | +.. _pymongo-fastapi: |
| 2 | +.. original URLs: |
| 3 | +.. - https://www.mongodb.com/developer/languages/java/java-single-collection-springpart1/ |
| 4 | +.. - https://www.mongodb.com/developer/languages/java/java-single-collection-springpart2/ |
| 5 | + |
| 6 | +======================== |
| 7 | +Single-Collection Design |
| 8 | +======================== |
| 9 | + |
| 10 | +.. facet:: |
| 11 | + :name: genre |
| 12 | + :values: reference |
| 13 | + |
| 14 | +.. meta:: |
| 15 | + :keywords: third party, integration, experience, orm, odm, spring, code example |
| 16 | + :description: Explore how to use a single-collection pattern to integrate the Java driver with Spring Data. |
| 17 | + |
| 18 | +.. contents:: On this page |
| 19 | + :local: |
| 20 | + :backlinks: none |
| 21 | + :depth: 2 |
| 22 | + :class: singlecol |
| 23 | + |
| 24 | +Overview |
| 25 | +-------- |
| 26 | + |
| 27 | +Single-collection designs in MongoDB offer a flexible and efficient way to model |
| 28 | +data by storing related documents in a single collection. This approach can |
| 29 | +simplify data access patterns and reduce the need for complex joins, which are |
| 30 | +not natively supported in MongoDB. |
| 31 | + |
| 32 | +Spring Data MongoDB bridges the gap between MongoDB’s flexible document model |
| 33 | +and Java’s strongly typed class system, making single-collection designs easier |
| 34 | +to implement, manage, and scale. In this guide you can learn how to implement |
| 35 | +single-collection designs in Java applications using Spring Data MongoDB. |
| 36 | + |
| 37 | +What Is a Single-Collection Design? |
| 38 | +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 39 | + |
| 40 | +A single-collection design stores multiple related entities in a |
| 41 | +single MongoDB collection. Each document in the collection can represent a |
| 42 | +different entity type, distinguished by a discriminator field. This design is |
| 43 | +particularly useful when entities share a common set of fields and are |
| 44 | +frequently accessed together. |
| 45 | + |
| 46 | +Tutorial: E-commerce Platform |
| 47 | +----------------------------- |
| 48 | + |
| 49 | +Consider an e-commerce platform where customers, sellers, and administrators are |
| 50 | +stored in the same collection. Each document includes a ``userType`` field to |
| 51 | +differentiate between the entity types: |
| 52 | + |
| 53 | +.. code-block:: json |
| 54 | + |
| 55 | + { |
| 56 | + "_id": ObjectId("64b8c123abc123"), |
| 57 | + "userType": "customer", |
| 58 | + "name": "Alice", |
| 59 | + |
| 60 | + "orders": [{"orderId": 1, "total": 100}] |
| 61 | + } |
| 62 | + |
| 63 | +.. code-block:: json |
| 64 | + |
| 65 | + { |
| 66 | + "_id": ObjectId("64b8c456abc456"), |
| 67 | + "userType": "seller", |
| 68 | + "name": "Bob's Store", |
| 69 | + |
| 70 | + "products": [{"productId": 101, "price": 20}] |
| 71 | + } |
| 72 | + |
| 73 | +.. code-block:: json |
| 74 | + |
| 75 | + { |
| 76 | + "_id": ObjectId("64b8c789abc789"), |
| 77 | + "userType": "admin", |
| 78 | + "name": "Charlie", |
| 79 | + |
| 80 | + "permissions": ["manageUsers", "manageOrders"] |
| 81 | + } |
| 82 | + |
| 83 | +This structure allows for efficient querying and updates, since all related data |
| 84 | +is contained in a single collection. |
| 85 | + |
| 86 | +Setting Up Spring Data MongoDB |
| 87 | +------------------------------ |
| 88 | + |
| 89 | +1. Add Dependencies |
| 90 | +~~~~~~~~~~~~~~~~~~~ |
| 91 | + |
| 92 | +Include the following dependency in your ``pom.xml`` to integrate Spring Data MongoDB: |
| 93 | + |
| 94 | +.. code-block:: xml |
| 95 | + |
| 96 | + <dependency> |
| 97 | + <groupId>org.springframework.boot</groupId> |
| 98 | + <artifactId>spring-boot-starter-data-mongodb</artifactId> |
| 99 | + </dependency> |
| 100 | + |
| 101 | +2. Configure MongoDB Connection |
| 102 | +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 103 | + |
| 104 | +In your ``application.properties``: |
| 105 | + |
| 106 | +.. code-block:: properties |
| 107 | + |
| 108 | + spring.data.mongodb.uri=mongodb://localhost:27017/yourDatabase |
| 109 | + |
| 110 | +Or define a custom configuration class: |
| 111 | + |
| 112 | +.. code-block:: java |
| 113 | + |
| 114 | + @Configuration |
| 115 | + public class MongoConfig extends AbstractMongoClientConfiguration { |
| 116 | + |
| 117 | + @Override |
| 118 | + protected String getDatabaseName() { |
| 119 | + return "yourDatabase"; |
| 120 | + } |
| 121 | + |
| 122 | + @Override |
| 123 | + public MongoClient mongoClient() { |
| 124 | + ConnectionString connectionString = new ConnectionString("mongodb://localhost:27017/yourDatabase"); |
| 125 | + MongoClientSettings mongoClientSettings = MongoClientSettings.builder() |
| 126 | + .applyConnectionString(connectionString) |
| 127 | + .build(); |
| 128 | + return MongoClients.create(mongoClientSettings); |
| 129 | + } |
| 130 | + } |
| 131 | + |
| 132 | +Defining the Domain Model |
| 133 | +-------------------------- |
| 134 | + |
| 135 | +Create a base class for common fields: |
| 136 | + |
| 137 | +.. code-block:: java |
| 138 | + |
| 139 | + public abstract class User { |
| 140 | + @Id |
| 141 | + private String id; |
| 142 | + private String name; |
| 143 | + private String email; |
| 144 | + private String userType; |
| 145 | + } |
| 146 | + |
| 147 | +Define subclasses for each user type: |
| 148 | + |
| 149 | +.. code-block:: java |
| 150 | + |
| 151 | + @Document(collection = "users") |
| 152 | + public class Customer extends User { |
| 153 | + private List<Order> orders; |
| 154 | + } |
| 155 | + |
| 156 | +.. code-block:: java |
| 157 | + |
| 158 | + @Document(collection = "users") |
| 159 | + public class Seller extends User { |
| 160 | + private List<Product> products; |
| 161 | + } |
| 162 | + |
| 163 | +.. code-block:: java |
| 164 | + |
| 165 | + @Document(collection = "users") |
| 166 | + public class Admin extends User { |
| 167 | + private List<String> permissions; |
| 168 | + } |
| 169 | + |
| 170 | +Implementing Repositories |
| 171 | +-------------------------- |
| 172 | + |
| 173 | +Create a repository interface for the ``User`` entity: |
| 174 | + |
| 175 | +.. code-block:: java |
| 176 | + |
| 177 | + public interface UserRepository extends MongoRepository<User, String> { |
| 178 | + List<User> findByUserType(String userType); |
| 179 | + } |
| 180 | + |
| 181 | +Service Layer Implementation |
| 182 | +---------------------------- |
| 183 | + |
| 184 | +Implement a service class to handle business logic: |
| 185 | + |
| 186 | +.. code-block:: java |
| 187 | + |
| 188 | + @Service |
| 189 | + public class UserService { |
| 190 | + |
| 191 | + @Autowired |
| 192 | + private UserRepository userRepository; |
| 193 | + |
| 194 | + public List<User> getUsersByType(String userType) { |
| 195 | + return userRepository.findByUserType(userType); |
| 196 | + } |
| 197 | + } |
| 198 | + |
| 199 | +Testing the Implementation |
| 200 | +-------------------------- |
| 201 | + |
| 202 | +In your test class: |
| 203 | + |
| 204 | +.. code-block:: java |
| 205 | + |
| 206 | + @SpringBootTest |
| 207 | + public class UserServiceTests { |
| 208 | + |
| 209 | + @Autowired |
| 210 | + private UserService userService; |
| 211 | + |
| 212 | + @Test |
| 213 | + public void testGetUsersByType() { |
| 214 | + List<User> customers = userService.getUsersByType("customer"); |
| 215 | + assertNotNull(customers); |
| 216 | + assertFalse(customers.isEmpty()); |
| 217 | + } |
| 218 | + } |
| 219 | + |
| 220 | +Benefits of Single-Collection Designs |
| 221 | +------------------------------------- |
| 222 | + |
| 223 | +- **Simplified Data Access**: All related data is stored in a single collection, reducing the need for joins. |
| 224 | +- **Improved Performance**: Fewer collections means fewer indexes to manage and faster queries in many use cases. |
| 225 | +- **Flexible Schema**: MongoDB’s schema-less nature enables storing different structures in the same collection. |
| 226 | +- **Easy Polymorphic Queries**: Query across all user types or filter by type using simple query parameters. |
| 227 | + |
| 228 | +Conclusion |
| 229 | +---------- |
| 230 | + |
| 231 | +Single-collection designs are a powerful modeling pattern in MongoDB that can simplify your application's persistence layer. |
| 232 | +Using Spring Data MongoDB in Java, you can implement this pattern with minimal configuration while maintaining strong typing and repository support. |
| 233 | + |
| 234 | +For more advanced scenarios—including handling polymorphism, aggregations, and validation—consider diving deeper into the Spring Data MongoDB documentation and the MongoDB schema design patterns. |
0 commit comments