$elemMatch 的 MongoDB 索引

2024-04-23

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

我正在执行如下查询:

{ lc: "eng", group: "xyz", indices: { $elemMatch: { text: "as", pos: { $gt: 1 } } } }

如果我添加一个索引

{lc:1, group:1, indices.text:1, indices.pos:1}

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


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

{
    "_id" : 1,
    "lc" : "eng",
    "group" : "xyz",
    "indices" : [
        {
            "text" : "as",
            "pos" : 2
        }, 
        {
            "text" : "text",
            "pos" : 4
        }
    ]
}

我使用这种格式的文档创建了一个测试集合,创建了索引,并运行您使用 .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"
}

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

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

$elemMatch 的 MongoDB 索引 的相关文章

随机推荐