Skip to content

Commit

Permalink
Merge pull request #40 from mongodb-developer/java-server-feedback
Browse files Browse the repository at this point in the history
Java server feedback
  • Loading branch information
dfreniche authored Feb 19, 2025
2 parents d25867f + f49e624 commit 987e690
Show file tree
Hide file tree
Showing 4 changed files with 183 additions and 11 deletions.
15 changes: 14 additions & 1 deletion docs/50-demo-app/3-configure.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ The file will automatically save, and the server will restart.
You need to start the server. Click on the terminal window and type:

```shell
$ mvn spring-boot:run
mvn spring-boot:run
```

</TabItem>
Expand All @@ -63,8 +63,21 @@ $ mvn spring-boot:run

In the *Terminal* tab at the bottom, look for the `Server is running on port: 5000` line. If you see it, you're good to go!

<Tabs groupId="server">
<TabItem value="node" label="🚀 NodeJS/Express">

<Screenshot url="https://github.com/mongodb-developer/library-management-system" src="img/screenshots/50-demo-app/3-configure/1-running.png" alt="The terminal panel" />

</TabItem>

<TabItem value="java" label="☕️ Java Spring Boot">

<Screenshot url="https://github.com/mongodb-developer/library-management-system" src="img/screenshots/50-demo-app/3-configure/1-running-java.png" alt="The terminal panel" />

</TabItem>
</Tabs>


## Reload the client

Now that the server is running, you can reload the client to see the application.
Expand Down
116 changes: 112 additions & 4 deletions docs/60-schema-validation/2-validate-users.mdx
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';

# 👐 Enable Validation for the Users Collection

In this exercise, you will explore the pre-written JSON validation schema for the `users` collection, run a script to apply it to the collection, and test the schema validation by inserting a document that does not match the schema.

:::info
Note for Java users: schema validation rules are typically applied via a Javascript script! Although there's nothing stopping us to write this code in Java, this is usually a DB Admin task.
:::

## Database user permissions

To update the validator for any database collection, your database user must have admin privileges. Follow these steps to ensure your user has the correct permissions:
Expand All @@ -22,8 +21,20 @@ Atlas will deploy the change in a few seconds.

## Explore the JSON schema

<Tabs groupId="server">
<TabItem value="node" label="🚀 NodeJS/Express">

The JSON schema for the `users` collection is stored in the `server/src/schema-validation/apply-schema.ts` [file](https://github.com/mongodb-developer/library-management-system/blob/main/server/src/schema-validation/apply-schema.ts). Open the file in your GitHub codespace and examine the schema.

</TabItem>

<TabItem value="java" label="☕️ Java Spring Boot">

JSON schema for the `users` collection:

</TabItem>
</Tabs>

```ts
const userSchema = {
bsonType: 'object',
Expand All @@ -49,6 +60,10 @@ The schema defines the following constraints:

## Explore the script to apply the schema


<Tabs groupId="server">
<TabItem value="node" label="🚀 NodeJS/Express">

Examine the lines immediately following the schema definition in the `apply-schema.ts` file. You will see a function that applies the schema to the `users` collection.

```js
Expand All @@ -73,8 +88,51 @@ The function uses the `db.command()` method to apply the schema to the `users` c
- If you set it to `error`, MongoDB rejects any insert or update that violates the validation criteria.
- If you set it to `warn`, the operation proceeds, but the violation is recorded in the MongoDB log.

</TabItem>

<TabItem value="java" label="☕️ Java Spring Boot">

```java
public void applySchemaValidation() {
try (MongoClient mongoClient = MongoClients.create(mongoDBURI)) {
MongoDatabase database = mongoClient.getDatabase("library");

Document userSchema = new Document("$jsonSchema", new Document()
.append("bsonType", "object")
.append("required", List.of("name", "isAdmin"))
.append("properties", new Document()
.append("name", new Document("bsonType", "string").append("minLength", 5)
.append("description", "must be a string and is required"))
.append("isAdmin", new Document("bsonType", "bool")
.append("description", "must be a boolean and is required"))
)
);

Document command = new Document("collMod", "users")
.append("validator", userSchema)
.append("validationLevel", "strict")
.append("validationAction", "error");

Document result = database.runCommand(command);

if (result.getDouble("ok") != 1.0) {
System.err.println("Failed to enable schema validation!");
System.exit(1);
} else {
System.out.println("Schema validation enabled!");
}
}
}
```

</TabItem>
</Tabs>

## Apply the schema to the `users` collection

<Tabs groupId="server">
<TabItem value="node" label="🚀 NodeJS/Express">

You need to run the script to apply the schema to the `users` collection.

1. Open a new terminal emulator tab in your GitHub codespace.
Expand Down Expand Up @@ -102,12 +160,42 @@ You need to run the script to apply the schema to the `users` collection.
Schema validation enabled!
```

</TabItem>

<TabItem value="java" label="☕️ Java Spring Boot">

1. Stop the running app.
1. Locate the bottom panel and click on the `TERMINAL` tab.
1. Press Ctrl+C to interrup the running app

1. Copy above code for `applySchemaValidation` as a method in the `LibraryApplication.java` class.
1. Modify the `run` method to call `applySchemaValidation`
```java
@Override
public void run(String... args) {
log.info("🚀 App Started");
applySchemaValidation();
}
```
1. Restart the app typing in the Terminal:

```bash
mvn spring-boot:start
```

</TabItem>
</Tabs>


:::caution
If you see an error related to your user permissions, go back to the [Database User Permissions](#database-user-permissions) section and update your user permissions.
:::

## Test the schema validation

<Tabs groupId="server">
<TabItem value="node" label="🚀 NodeJS/Express">

Now that the schema validation is enabled for the `users` collection, you can test it by inserting a document that does not match the schema.

1. Open the file `server/src/schema-validation/test-validation.ts` [file](https://github.com/mongodb-developer/library-management-system/blob/main/server/src/schema-validation/test-validation.ts).
Expand All @@ -122,6 +210,26 @@ The error describes that the `name` and `isAdmin` fields are required but missin

Modify the script to insert a document again with the `name` and `isAdmin` fields and you should see the document inserted successfully.


</TabItem>

<TabItem value="java" label="☕️ Java Spring Boot">

Now that the schema validation is enabled for the `users` collection, you can test it by inserting a document that does not match the schema, or you can check the Validation tab in Compass to check for the new validation rules.

You can also check it in the mongosh typing:

```
db.getCollectionInfos({ name: "users" })
```

If schema validation is not enabled, the "validator" field will be missing or empty.


</TabItem>
</Tabs>


## Summary

In this exercise, you explored the JSON schema for the `users` collection, ran a script to apply the schema to the collection, and tested the schema validation by inserting a document that does not match the schema.
Expand Down
63 changes: 57 additions & 6 deletions docs/70-indexing/1-create-compound-index.mdx
Original file line number Diff line number Diff line change
@@ -1,16 +1,19 @@
# 👐 Build a compound index following the ESR rule
import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';

:::info
Note for Java users: we will create indexes via a Javascript script! Although there's nothing stopping us to write this code in Java, this is usually a DB Admin task.
:::
# 👐 Build a compound index following the ESR rule

In this exercise, you will build a compound index following the ESR rule, compare the query explain plans before and after creating the index, and analyze them.

## Explore the code


<Tabs groupId="server">
<TabItem value="node" label="🚀 NodeJS/Express">

1. Open the file `server/src/indexing/borrowed-books-index.ts` [file](https://github.com/mongodb-developer/library-management-system/blob/main/server/src/indexing/borrowed-books-index.ts) in your GitHub Codespace.

2. Examine the code to build a compound index on the `borrowedBooks` collection.
2. Examine the code to build a compound index on the `issueDetails` collection.

```js
/**
Expand All @@ -33,7 +36,7 @@ In this exercise, you will build a compound index following the ESR rule, compar
```
:::info
The index is created on the `borrowedBooks` collection to support the query that finds the issue details for a user with a specific `userID`, where the `borrowDate` is greater than or equal to a specific `date`, and sorts the results by `returnedDate` in descending order.
The index is created on the `issueDetails` collection to support the query that finds the issue details for a user with a specific `userID`, where the `borrowDate` is greater than or equal to a specific `date`, and sorts the results by `returnedDate` in descending order.
This is compound index and it follows the ESR rule: Equality, Sort, and Range. This ensures optimal performance for the query.
:::
Expand Down Expand Up @@ -73,6 +76,54 @@ In this exercise, you will build a compound index following the ESR rule, compar
Notice the difference in the winning plan stage and the number of documents examined before and after creating the index.
:::


</TabItem>

<TabItem value="java" label="☕️ Java Spring Boot">

1. Open the file `java-server/java-server/src/main/java/com/mongodb/devrel/library/model/IssueDetail.java` [file](https://github.com/mongodb-developer/library-management-system/blob/java-server/java-server/src/main/java/com/mongodb/devrel/library/model/IssueDetail.java) in your GitHub Codespace.

1. Examine the code to build a compound index on the `issueDetails` collection.

```java
// add these imports
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.index.CompoundIndex;

// ...
// Add the CompoundIndex annotation
@CompoundIndex(name = "user_returned_borrow_idx", def = "{'user._id': 1, 'returnedDate': 1, 'borrowDate': 1}")
public class IssueDetail {
// ...

// Constructors, Getters, Setters
}
```

:::info
The index is created on the `issueDetails` collection to support the query that finds the issue details for a user with a specific `userID`, where the `borrowDate` is greater than or equal to a specific `date`, and sorts the results by `returnedDate` in descending order.

This is compound index and it follows the ESR rule: Equality, Sort, and Range. This ensures optimal performance for the query.
:::
1. Add to `application.properties` this line to enable automatic creation of indexes

```
spring.data.mongodb.auto-index-creation=true
```
1. Stop the running app.
1. Locate the bottom panel and click on the `TERMINAL` tab.
1. Press Ctrl+C to interrup the running app

1. Restart the app typing in the Terminal:

```bash
mvn spring-boot:start
```

</TabItem>
</Tabs>


## 🦸‍♀️ Try different indexes

Modify the compound index by adding and removing fields, and observe the changes in the query explain plans.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

0 comments on commit 987e690

Please sign in to comment.