Skip to content

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

@vipcxj

Description

@vipcxj
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.

Metadata

Metadata

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions