Dynamic Collection Handler
In database application development, sometimes we need to query different collections based on various conditions. Mongo-Plus provides a dynamic collection handler
CollectionNameHandler
, which allows us to dynamically change the collection name in MongoDB statements at runtime. This is particularly useful for handling sharding logic.
CollectionNameHandler
- Interface for dynamic collection handling
String dynamicCollectionName(ExecuteMethodEnum, Object[], MongoNamespace)
: Parameters correspond to the method enum, method arguments, and namespace.
Example
Implement the CollectionNameHandler
interface, create a dynamic collection handler, and register it as a Bean. In this example, if the query parameter contains userName
and its value is 张三
, the collection name is changed to user_zhangsan
.
java
@Component
public class CustomCollectionNameHandler implements CollectionNameHandler {
@Override
public String dynamicCollectionName(ExecuteMethodEnum executeMethodEnum, Object[] source, MongoNamespace namespace) {
if (executeMethodEnum == ExecuteMethodEnum.QUERY) {
// Convert parameters according to com.mongoplus.execute.Execute interface
// For example, executeQuery(Bson, BasicDBObject, BasicDBObject, Class<T>, MongoCollection<Document>)
// The 0th parameter type is Bson
Bson bson = (Bson) source[0];
BsonString userName = bson.toBsonDocument().getString("userName", new BsonString(""));
// If userName == 张三
if (userName.getValue().equals("张三")) {
// Return new collection name: user_zhangsan
return "user_zhangsan";
}
}
// Return original collection name if conditions not met
return namespace.getCollectionName();
}
}