I have a scenario where depending on an incoming request’s HTTP header, I need to attach an additional filter to the query (Collection.find()), and when creating a new document I would like to set an additional field to document when saving to the DB.
We have close to 30+ Spring boot microservices that need to accommodate a change, depending on the incoming “tenant” HTTP header we need to filter the data by adding the tenant field query filter.
I am looking for a Mongo query interceptor where I can attach the additional filter to the in-flight Mongo query that is being sent to the server.
I tried utilizing
CommandListener#commandStarted(CommandStartedEvent event)
to update the query but that doesn’t seem to update the query (immutable?). Most implementations I came across are reading/logging the event but none are updating the event command.
Is this achievable with Mongo core java driver (version: 4.3.1 Java driver)?
Appreciate any pointers
@Override
public void commandStarted(CommandStartedEvent event) {
final String tenantId = threadContext.get(CONTEXT_REQUEST_HEADER_PREFIX + HEADER_TENANT_ID);
String commandName = event.getCommandName();
final BsonDocument command = event.getCommand();
if ("find".equals(commandName)) {
BsonDocument tenantFilter = new BsonDocument("metaInfo.tenantId", new BsonString(tenantId));
final BsonDocument filter = command.getDocument("filter");
final BsonDocument append = filter.append("metaInfo.tenantId", tenantFilter);
event = new CommandStartedEvent(event.getRequestId(), event.getConnectionDescription(),
event.getDatabaseName(), event.getCommandName(), append);
}
}