如何将 spring data mongo @CompoundIndex 与子集合一起使用? [英] How to use spring data mongo @CompoundIndex with sub collections?
本文介绍了如何将 spring data 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 的复合索引?
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'}")
提前致谢.
推荐答案
我已经在我的应用程序中尝试过这种复合索引,它也使用了 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 data mongo @CompoundIndex 与子集合一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文