spring-projects / spring-projects/spring-data-mongodb

@Aggregation not work for { $group: { _id: $XXX } }

Open
#5,058 3 comments 0 reactions 1 assignee View on GitHub

@christophstrobl is already working on this.

Since Sep 15, 2025.

type: bug
Dominant language
Java
Stars
1.7k
Forks
1.1k
PR merge metrics
No merged PRs in 30d

Description

public interface ResourceRepository
        extends ReactiveMongoRepository<Resource, String>, ReactiveQuerydslPredicateExecutor<Resource> {
    @Aggregation(pipeline = {
            "{ $match: { sha256: ?0, completed: true } }",
            "{ $group: { _id: $refId, count: { $sum: 1 }, ids: { $push: $_id } } }",
            "{ $project: { _id: 1, count: 1, ids: 1, sortKey: { $cond: { if: { $eq: ['$_id', null] }, then: -Infinity, else: '$count' } } } }",
            "{ $sort: { sortKey: -1 } }",
            "{ $group: { _id: null, mostFrequent: { $first: '$$ROOT' }, allGroups: { $push: '$$ROOT' } } }",
            "{ $project: { refId: '$mostFrequent._id', ids: { $reduce: { input: { $filter: { input: '$allGroups', cond: { $or: [{ $eq: ['$mostFrequent._id', null] }, { $ne: ['$$this._id', '$mostFrequent._id'] }] } } }, initialValue: [], in: { $concatArrays: ['$$value', '$$this.ids'] } } }, _id: 0 } }"
    })
    Mono<RefIdResult> findMostFrequentRefIdWithIds(String sha256);
}

Here is my method.
And when invoking it, an error occured:

org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [org.bson.types.ObjectId] for value [$refId]

After debug, I found the problem here (QueryMapper.class):

				Field field = createPropertyField(entity, key, mappingContext);  // here it created a field point to Resource.id, becuase key == '_id'

				// TODO: move to dedicated method
				if (field.getProperty() != null && field.getProperty().isUnwrapped()) {

					Object theNestedObject = BsonUtils.get(query, key);
					Document mappedValue = (Document) getMappedValue(field, theNestedObject);
					if (!StringUtils.hasText(field.getMappedKey())) {
						result.putAll(mappedValue);
					} else {
						result.put(field.getMappedKey(), mappedValue);
					}
				} else {

					Entry<String, Object> entry = getMappedObjectForField(field, BsonUtils.get(query, key)); // BsonUtils.get(query, key) == '$refId', spring-data-mongodb think $refId is an ObjectId, and convert it to ObjectId by new ObjectId("$refId"), and failed.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.