How to find collections by its nested object's objectId in Spring Data using repository interface?
I've figured out how to solve this.
Change the parameter type to org.bson.types.ObjectId; from String
public List<SomeObject> findByNestedObjectId(ObjectId id);
and when you call it use
repositoryName.findByNestedObjectId(new ObjectId(theIdString));
Spring-data-mongodb
would not convert _id field to ObjectId type automatically in nested class on query operation. You should convert it manually. For example:
public List<SomeObject> findByNestedObjectId(String id) {
Query query = Query.query(new Criteria("nestedObject._id", convertToObjectId(id)));
return mongoTemplate.find(query, SomeObject.class);
}
Object convertToObjectId(Object id) {
if (id instanceof String && ObjectId.isValid(id)) {
return new ObjectId(id);
}
return id;
}
If NestedObject
looks like this:
class NestedObject {
@Id String id;
}
and the String
value you hand into the query is a valid ObjectId
the query:
findByNestdObjectId(String id);
should work. If it doesn't feel free to create a ticket in out JIRA and provide a tiny test case to reproduce it.