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

greg picture greg · Aug 22, 2014 · Viewed 19.3k times · Source

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 {
    @Id
    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
}

Now, 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

Ramon Rahman picture Ramon Rahman · Dec 9, 2015

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));