Spring Data Mongo Custom Repository Query with ObjectID

As the accepted solution did not yield any results in my case, I had to find another solution, that was:

Instead of using the autogenerated query functionality defined via @Query(...) I opted for manually building the DBObject used to query mongo, and defining the functionality as a default implementation in the interface, thus keeping it "clean" (" - because had to introduce a _query method)

Note: This solution only works in Java 1.8+

public interface SomeRepository extends MongoRepository<SomeEntity, String> {

    @Query("{'nestedEntity._id': ?0}")
    SomeEntity findByNestedEntityId_DoesntWork(String nestedEntityId);

    @Query("?0")
    SomeEntity _query(DBObject query);

    default SomeEntity findByNestedEntityId(String nestedEntityId) {
        DBObject queryObject = BasicDBObjectBuilder
            .start("nestedEntity._id", new ObjectId(nestedEntityId))
            .get();

        return this._query(queryObject);
    }
}

Try this

@Query("{ 'items': { $elemMatch: { 'refund.id' :  ?0 } } }")
RMA findRMAByItemRefund(String refundId);

From my experience, ?0 should standalone and not used as a mongo function parameter.

Also, is $id your own assumption or the field is actually stored as $id. If not, I will go with refund.id


I guess my problem was a little different, but since I couldn't find answer anywhere, I believe it's worth mentioning. Basically I wanted to do the search by ObjectId AND userId, so here's what I've done:

@Query("{ '_id': ?0, 'userId': ?1 }")
T findByObjectIdAndUserId(final ObjectId objectId, final Long userId);