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

6

我正在尝试弄清楚如何构建查询语句以便能够命中我的索引。我的文档结构如下:

{ "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" : {

}
}

有没有一种方法可以让文档样式查询命中索引?原因是,当从我的持久化对象构建查询时,将它们序列化为文档要比使用点符号的内容更容易。我还要补充的是,我们正在使用一个使用Jackson构建的自定义数据映射层。是否使用像Morphia这样的工具有助于正确构建这些查询?
1个回答

7

我进行了更多的调查,这个帖子解释了子文档查询的原理。我上面的问题是,为了使基于子文档的查询像点符号一样工作,我需要使用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"
        ]
    ]
}
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接