Skip to content

Commit f8a3127

Browse files
committed
first draft
1 parent da7d89f commit f8a3127

File tree

4 files changed

+274
-0
lines changed

4 files changed

+274
-0
lines changed

snooty.toml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@ toc_landing_pages = [
1919
"/api-documentation",
2020
"/security",
2121
"/security/auth",
22+
"/integrations",
23+
"/integrations/spring-data"
2224
]
2325

2426
sharedinclude_root = "https://raw.githubusercontent.com/10gen/docs-shared/main/"

source/integrations.txt

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,10 @@ Third-Party Integrations
1818
:depth: 2
1919
:class: singlecol
2020

21+
.. toctree::
22+
23+
Spring Data Integration </integrations/spring-data>
24+
2125
Overview
2226
--------
2327

source/integrations/spring-data.txt

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
===================
2+
Spring Data MongoDB
3+
===================
4+
5+
.. facet::
6+
:name: genre
7+
:values: reference
8+
9+
.. meta::
10+
:keywords: third party, integration, experience, orm, odm
11+
:description: Explore how to integrate the Java driver with Spring Data.
12+
13+
.. contents:: On this page
14+
:local:
15+
:backlinks: none
16+
:depth: 2
17+
:class: singlecol
18+
19+
.. toctree::
20+
21+
Single-Collection Design </integrations/spring-data/single-collection-design>
22+
23+
`Spring Data MongoDB <https://spring.io/projects/spring-data-mongodb>`__ is a
24+
part of the larger Spring Data project that provides a
25+
high-level, consistent, and convenient way to interact with MongoDB from Java
26+
applications. It simplifies database operations by offering repository
27+
abstractions, custom query derivation, and seamless mapping of Java objects to
28+
MongoDB documents using annotations.
29+
30+
Spring Data MongoDB because can reduce boilerplate code, integrate smoothly with the Spring ecosystem
31+
(including Spring Boot), and support both imperative and reactive programming
32+
models. It is commonly used for building scalable applications that require flexible
33+
schema handling and fast development cycles, while benefiting from strong
34+
typing and Spring’s dependency injection and configuration capabilities.
Lines changed: 234 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,234 @@
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+
"email": "[email protected]",
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+
"email": "[email protected]",
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+
"email": "[email protected]",
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

Comments
 (0)