# Usage

### Spring / Spring Boot Projects

1. Create a custom `MongoTemplate` bean using the snippet given below.

{% code overflow="wrap" %}

```java
package com.alpha.mongodb.sharding.example.configuration;

@Configuration
public class CollectionShardedMongoConfiguration {

    @Bean("collectionShardedMongoTemplate")
    public MongoTemplate collectionShardedMongoTemplate(
            @Autowired MongoDatabaseFactory collectionShardedMongoDbFactory) {

        CollectionShardingOptions shardingOptions =
                CollectionShardingOptions.withIntegerStreamHints(
                        IntStream.range(0, 3));
        return new CollectionShardedMongoTemplate(
                collectionShardedMongoDbFactory(), shardingOptions);
    }
}
```

{% endcode %}

2. Implement your entity classes from `CollectionShardedEntity`. If this is not a feasible approach for you, then you can always register a `HintResolutionCallback` to `ShardingOptions` and use it. See the section below to get an example usage of Hint Resolution Callback.

{% code overflow="wrap" %}

```java
// Sample TestShardedEntity
@Document("TEST")
@Data
@FieldNameConstants
public class TestShardedEntity implements CollectionShardedEntity {

    @Id
    private String id;

    @Indexed(unique = true)
    private String indexedField;

    @Override
    public String resolveCollectionHint() {
        return String.valueOf(indexedField.charAt(1) - '0');
    }
}
```

{% endcode %}

3. Autowire the `collectionShardedMongoTemplate` and use it wherever required.

#### **Using Sharding Hint**

In order to route the write queries, the entities are supposed to implement from CollectionShardedEntity. But, the find queries can take place with different criterion, with different fields. In order to route the find query to the right collection, sharding hint is used.

{% code overflow="wrap" %}

```java
import java.util.Optional;

public class TestRepository {

    @Autowired
    @Qualifier("collectionShardedMongoTemplate")
    private MongoTemplate collectionShardedMongoTemplate;

    public Optional<TestShardEntity> findById() {
        ShardingHintManager.setCollectionHint("3");
        return Optional.ofNullable(
                collectionShardedMongoTemplate.findById(
                        "6427b9327a2cad734d5ff051",
                        TestShardEntity.class));
    }
}
```

{% endcode %}

{% hint style="info" %}
If the sharding hint is not set, methods will throw a `UnresolvableShardException`.
{% endhint %}

#### **Using `HintResolutionCallback`**

You can extend your entities from `CollectionShardedEntity` to resolve the sharding hint whenever an entity context is passed to the queries. This can also be done using HintResolution callback which a provides couple of methods to resolve hint.

For an entity that is not extending from `CollectionShardedEntity` a callback can be registered with Sharding Options by calling `ShardingOptions::setHintResolutionCallbacks`. If the callbacks are defined as spring beans they are automatically discovered during initializing application context.

{% code overflow="wrap" %}

```java
@Data
@org.springframework.data.mongodb.core.mapping.Document("TEST1")
@FieldNameConstants
public class TestEntity1 {
    @Id
    private String id;

    @Indexed(unique = true)
    private String indexedField;

    public static class TestEntity1HintResolutionCallback implements HintResolutionCallback<TestEntity1> {

        @Override
        public ShardingHint resolveHintForFindContext(Document query, Class<TestEntity1> entityClass) {
            return ShardingHint.withCollectionHint("0");
        }

        @Override
        public ShardingHint resolveHintForSaveContext(TestEntity1 entity) {
            return ShardingHint.withCollectionHint("0");
        }
    }
}
```

{% endcode %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://shashankrnr32.gitbook.io/mongodb-application-sharding/sharding-strategies/collection-sharding-strategy/usage.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
