Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

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

Assume that I have such entities like the following:

@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;
  ...
}

is it possible to use a compoundIndex with respect to A.id AND B.id together?

I mean maybe like:

@CompoundIndex(name = "aid_bid_idx", def = "{'id', 'b.id'}")

Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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",
    ...
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...