Skip to content

Expose MongoClient from within MongoTemplate #5105

@strogiyotec

Description

@strogiyotec

Hello everyone,
MongoDB Java Driver 5.6.0 introduced a new API in MongoClient

void appendMetadata(MongoDriverInformation mongoDriverInformation);

This API allows end users to dynamically append metadata that later becomes visible in MongoDB Atlas. One important use case is allowing an application or framework to annotate itself with identifying metadata so teams can track slow queries per service.
The MongoDB driver team is also using this API internally to capture which framework is being used (e.g., Spring Data).

Background (previous driver behavior)

Before this new API existed, the driver relied on the following factory method to attach metadata:

public static MongoClient create(
        final ConnectionString connectionString,
        @Nullable final MongoDriverInformation mongoDriverInformation
)

Frameworks such as Spring Data MongoDB use this factory to populate metadata (e.g., reporting spring-data as the driver name).

What problem does the new API solve?

When the framework does not directly control the creation of MongoClient, there is no reliable way for the driver to detect which framework is actually being used.

Example:
In LangChain4j, users have create their own MongoClient instances manually. Because of that we made a commit to call append after the MongoClient was already initiated

The issue we face with Spring AI MongoDB

In Spring Data MongoDB:
MongoClient is not exposed as a Spring bean.
The starter typically accepts a URL and internally constructs a MongoTemplate
In projects like spring-ai-mongodb-atlas-store, a MongoTemplate instance is passed into a MongoDBAtlasVectorStore.
Because neither MongoTemplate nor MongoDatabaseFactory exposes a public API for the underlying MongoClient, it is currently impossible for us(Mongo team) to call appendMetadata(...) to annotate that the user is running Spring AI.

Proposal

We would like to propose the following enhancements:

  1. Expose the underlying MongoClient inside MongoTemplate, e.g. by making it a field.
  2. Introduce a new getMongoClient method within MongoTemplate
    From spring-ai , mongo team will be able to append metadata by using this new get method
	protected MongoDBAtlasVectorStore(Builder builder) {
		super(builder);

		Assert.notNull(builder.mongoTemplate, "MongoTemplate must not be null");
               builder.mongoTemplate.getMongoClient.appendMetadata("spring-ai");

Thank you!

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions