$ elemMatch的MongoDB索引

Nic*_*ell 10 indexing mongodb

http://www.mongodb.org/display/DOCS/Indexes上的索引帮助页面没有提到$ elemMatch,因为在我的2M +对象集合上添加索引的天数我想我会问这个:

我正在做一个查询:

{ lc: "eng", group: "xyz", indices: { $elemMatch: { text: "as", pos: { $gt: 1 } } } }
Run Code Online (Sandbox Code Playgroud)

如果我添加一个索引

{lc:1, group:1, indices.text:1, indices.pos:1}
Run Code Online (Sandbox Code Playgroud)

这个带有$ elemMatch组件的查询能够完全通过索引运行吗?

Mar*_*arc 19

根据您的查询,我想您的文档看起来像这样:

{
    "_id" : 1,
    "lc" : "eng",
    "group" : "xyz",
    "indices" : [
        {
            "text" : "as",
            "pos" : 2
        }, 
        {
            "text" : "text",
            "pos" : 4
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

我使用此格式的文档创建了一个测试集合,创建了索引,并运行了使用.explain()选项发布的查询.

索引按预期使用:

> db.test.ensureIndex({"lc":1, "group":1, "indices.text":1, "indices.pos":1})
> db.test.find({ lc: "eng", group: "xyz", indices: { $elemMatch: { text: "as", pos: { $gt: 1 } } } }).explain()
{
    "cursor" : "BtreeCursor lc_1_group_1_indices.text_1_indices.pos_1",
    "isMultiKey" : true,
    "n" : NumberLong(1),
    "nscannedObjects" : NumberLong(1),
    "nscanned" : NumberLong(1),
    "scanAndOrder" : false,
    "indexOnly" : false,
    "nYields" : 0,
    "nChunkSkips" : NumberLong(0),
    "millis" : 0,
    "indexBounds" : {
        "lc" : [
            [
                "eng",
                "eng"
            ]
        ],
        "group" : [
            [
                "xyz",
                "xyz"
            ]
        ],
        "indices.text" : [
            [
                "as",
                "as"
            ]
        ],
        "indices.pos" : [
            [
                {
                    "$minElement" : 1
                },
                {
                    "$maxElement" : 1
                }
            ]
        ]
    },
    "server" : "Marcs-MacBook-Pro.local:27017"
}
Run Code Online (Sandbox Code Playgroud)

有关.explain()功能的文档可以在这里找到:http://www.mongodb.org/display/DOCS/Explain

.explain()可用于显示有关查询的信息,包括使用哪个(如果有)索引.

  • 该索引用于此查询.未执行集合扫描.我们知道正在使用索引,因为它是在"cursor"字段中给出的."仅索引"仅表示返回的数据完全在索引中,并且不需要读取文档本身.根据我之前的评论,使用多键索引是不可能的.有关详细信息,请参阅"检索字段子集"文档的"涵盖索引"部分.http://www.mongodb.org/display/DOCS/Retrieving+a+Subset+of+Fields#RetrievingaSubsetofFields-CoveredIndexes (3认同)