MongoDB indexes for $elemMatch

2020-06-09 07:27发布

问题:

The indexes help page at http://www.mongodb.org/display/DOCS/Indexes doesn't mention $elemMatch and since it says to add an index on my 2M+ object collection I thought I'd ask this:

I am doing a query like:

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

If I add an index

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

will this query with the $elemMatch component be able to be fully run through the index?

回答1:

Based on your query, I imagine that your documents look something like this:

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

I created a test collection with documents of this format, created the index, and ran the query that you posted with the .explain() option.

The index is being used as expected:

> 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"
}

The documentation on the .explain() feature may be found here: http://www.mongodb.org/display/DOCS/Explain

.explain() may be used to display information about a query, including which (if any) index is used.