MongoDB - 使用索引查询嵌套字段

时间:2012-03-14 15:37:51

标签: mongodb

我试图弄清楚我必须如何构建查询,以便它们能够达到我的索引。 我的文档结构如下:

{ "attributes" : { "make" : "Subaru", "color" : "Red" } }

索引为:db.stuff.ensureIndex({"attributes.make":1})

我发现使用点表示法查询会查找索引,而查询文档则不会。

示例:

db.stuff.find({"attributes.make":"Subaru"}).explain()
{
"cursor" : "BtreeCursor attributes.make_1",
"nscanned" : 2,
"nscannedObjects" : 2,
"n" : 2,
"millis" : 0,
"nYields" : 0,
"nChunkSkips" : 0,
"isMultiKey" : false,
"indexOnly" : false,
"indexBounds" : {
    "attributes.make" : [
        [
            "Subaru",
            "Subaru"
        ]
    ]
}
}

VS

db.stuff.find({attributes:{make:"Subaru"}}).explain()
{
"cursor" : "BasicCursor",
"nscanned" : 2,
"nscannedObjects" : 2,
"n" : 0,
"millis" : 1,
"nYields" : 0,
"nChunkSkips" : 0,
"isMultiKey" : false,
"indexOnly" : false,
"indexBounds" : {

}
}

有没有办法让文档样式查询命中索引?原因是当从我的持久对象构造查询时,将它们作为文档序列化更容易,而不是使用点表示法。

我还要补充一点,我们正在使用杰克逊构建的本土数据映射器层。使用像Morphia这样的东西有助于正确构建这些查询吗?

1 个答案:

答案 0 :(得分:7)

进行了更多的挖掘和this thread解释了子文档查询的内容。我上面的问题是,使基于子文档的查询的行为类似于我需要使用elemMatch的点符号。

db.stuff.find({"attributes":{"$elemMatch" : {"make":"Subaru"}}}).explain()
{
"cursor" : "BtreeCursor attributes.make_1",
"nscanned" : 2,
"nscannedObjects" : 2,
"n" : 0,
"millis" : 2,
"nYields" : 0,
"nChunkSkips" : 0,
"isMultiKey" : false,
"indexOnly" : false,
"indexBounds" : {
    "attributes.make" : [
        [
            "Subaru",
            "Subaru"
        ]
    ]
}
}