title: Spring Data Mongo - How to query by @DBRef field's id
body: <p>I am new to Spring Data Mongo so I must be doing something wrong because I can't manage to execute such a simple query. This is my model:</p>
  
  <pre><code>@Document(collection="brands")
  public class Brand{
      @Id
      private int id;
  
      private String name;
      ...
      //getters-setters
  }
  
  @Document(collection="models")
  public class Model{
      @Id
      private int id;
      private String name;
      @DBRef
      private Brand brand;
      ...
      //getters-setters
  }
  </code></pre>
  
  <p>I would like to get all models from a brand, so I implement the DAO as follows:</p>
  
  <pre><code>@Repository
  public interface IModelDAO extends MongoRepository&lt;Model, Integer&gt;{
      @Query(value="{ 'brand.$id' : ?0 }")
      public List&lt;Model&gt; findByBrandId(Integer id);   
  }
  </code></pre>
  
  <p>If I execute this mongodb query in the shell it works: <code>db.modelss.find({ 'brand.$id' : 1 })</code></p>
  
  <p>But, the Java application throws the following exception:</p>
  
  <pre><code>Caused by: java.lang.IllegalAccessError
  at org.springframework.data.mapping.PropertyReferenceException.detectPotentialMatches(PropertyReferenceException.java:134)
  </code></pre>
  
  <p>Apparently it is looking for a field $id in Brand class, and since it doesn't exist it fails. So I change the query to the following, so that it navigates to the id field:</p>
  
  <pre><code>@Query(value="{ 'brand.id' : ?0 }")
  </code></pre>
  
  <p>Now, it doesn't throw an exception but it doesn't find anything in the DB. </p>
  
  <p>Debugging the MongoTemplate.executeFindMultiInternal() method in can see that in</p>
  
  <pre><code>DBCursor cursor = null;
      try {
          cursor = collectionCallback.doInCollection(getAndPrepareCollection(getDb(), collectionName));
  </code></pre>
  
  <p>cursor's query is <code>query={ "brand" : 134}</code>. So it makes sense it doesn't find anything. Changing the query value during debugging to query={ "brand.$id" : 134} it works.</p>
  
  <p>So, why isn't the query correctly translated?</p>