How to use spring data mongo @CompoundIndex with sub collections?

后端 未结 2 1056
失恋的感觉
失恋的感觉 2020-12-30 10:57

Assume that I have such entities like the following:

@Document(collection = \"doc_a\")
public class A {    
  @Field(\"id\")
  private Integer id;

  @Field(         


        
相关标签:
2条回答
  • 2020-12-30 11:32

    I've tried this kind of compound index in my app, that use spring data too, and worked properly. You only have to correct the index definition in @CompoundIndex annotation:

    @CompoundIndex(name = "aid_bid_idx", def = "{'id' : 1, 'b.id' : 1}")
    @Document(collection = "doc_a")
    public class A {    
      @Field("id")
      private Integer id;
    
      @Field("b")
      private Collection<B> b;
      ...
    }
    
    public class B {    
      @Field("id")
      private Integer id;
      ...
    } 
    

    If you run a query with explain (like the follows) in mongo shell, you'll see that the index *aid_bid_idx* will be used.

    db.doc_a.find({ "id" : 1, "b.id" : 1}).explain()
    

    The result will be something like this:

    {
        "cursor" : "BtreeCursor aid_bid_idx",
        ...
    }
    
    0 讨论(0)
  • 2020-12-30 11:32

    I had the same problem, for me the Miguel's solution worked but I had to wrap the @CompoundIndex inside a @CompoundIndexes otherwise it didn't work (I'm using Spring Roo).

    @CompoundIndexes({
        @CompoundIndex(name = "aid_bid_idx", def = "{'id' : 1, 'b.id' : 1}")
    })
    @Document(collection = "doc_a")
    public class A {...}
    
    0 讨论(0)
提交回复
热议问题