如何在子集合中使用spring数据mongo @CompoundIndex? [英] How to use spring data mongo @CompoundIndex with sub collections?

查看:67
本文介绍了如何在子集合中使用spring数据mongo @CompoundIndex?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我拥有如下实体:

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

是否可以将有关A.id和B.id的compoundIndex一起使用?

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

我的意思可能是:

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

谢谢.

推荐答案

我在我的应用程序中尝试了这种复合索引,该索引也使用spring数据,并且工作正常. 您只需要更正@CompoundIndex批注中的索引定义:

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

如果在mongo shell中运行带有explain的查询(如下所示),您将看到将使用索引* aid_bid_idx *.

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

结果将是这样的:

{
    "cursor" : "BtreeCursor aid_bid_idx",
    ...
}

这篇关于如何在子集合中使用spring数据mongo @CompoundIndex?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆