greg greg - 1 year ago 129
Java Question

How to find collections by its nested object's objectId in Spring Data using repository interface?

I have a collection in MongoDB that has items like this one:

"_id" : ObjectId("53e4d31d1f6b66e5163962e3c"),
"name" : "bob",
"nestedObject" : {
"_id" : ObjectId("53f5a623cb5e4c1ed4f6ce67")
//more fields...

Java representation of this item looks following:

public class SomeObject {
private String id;
private String name;
private NestedObject nestedObject;

//getters and setters

The Repository interface is defined like this:

public interface SomeObjectRepository extends MongoRepository<SomeObject, String> {
public List<SomeObject> findByName(String name);
public List<SomeObject> findByNestedObjectId(String id);
//some other find functions

findByName(String name)
is working as it should be, but
findByNestedObjectId(String id)
returns nothing.

Question is: is it possible to find collection items by it's nested object's attribute using repository interface? If not, what is the recommended way to approach this problem? Is it possible without reimplementing whole repository?

Answer Source

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;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download