Improve querying fields exist in MongoDB

前端 未结 4 423
挽巷
挽巷 2020-12-05 20:03

I\'m in progress with estimation of MongoDB for our customers. Per requirements we need associate with some entity ent variable set of name-value pairs.

4条回答
  •  星月不相逢
    2020-12-05 20:58

    I think a sparse index is the answer to this, although you'll need an index for each field. http://www.mongodb.org/display/DOCS/Indexes#Indexes-SparseIndexes

    Sparse indexes should help with $exists:true queries.

    Even still, if your field is not really sparse (meaning it's mostly set), it's not going to help you that much.

    Update I guess I'm wrong. Looks like there's an open issue ( https://jira.mongodb.org/browse/SERVER-4187 ) still that $exists doesn't use sparse indexes. However, you can do something like this with find and sort, which looks like it properly uses the sparse index:

    db.ent.find({}).sort({a:1});
    

    Here's a full demonstration of the difference, using your example values:

    > db.ent.insert({'a':5775, 'b':'b1'})
    > db.ent.insert({'c':'its a c', 'b':'b2'})
    > db.ent.insert({'a':7557, 'c':'its a c'})
    > db.ent.ensureIndex({a:1},{sparse:true});
    

    Note that find({}).sort({a:1}) uses the index (BtreeCursor):

    > db.ent.find({}).sort({a:1}).explain();
    {
    "cursor" : "BtreeCursor a_1",
    "nscanned" : 2,
    "nscannedObjects" : 2,
    "n" : 2,
    "millis" : 0,
    "nYields" : 0,
    "nChunkSkips" : 0,
    "isMultiKey" : false,
    "indexOnly" : false,
    "indexBounds" : {
        "a" : [
            [
                {
                    "$minElement" : 1
                },
                {
                    "$maxElement" : 1
                }
            ]
        ]
    }
    }
    

    And find({a:{$exists:true}}) does a full scan:

    > db.ent.find({a:{$exists:true}}).explain();
    {
    "cursor" : "BasicCursor",
    "nscanned" : 3,
    "nscannedObjects" : 3,
    "n" : 2,
    "millis" : 0,
    "nYields" : 0,
    "nChunkSkips" : 0,
    "isMultiKey" : false,
    "indexOnly" : false,
    "indexBounds" : {
    
    }
    }
    

    Looks like you can also use .hint({a:1}) to force it to use the index.

    > db.ent.find().hint({a:1}).explain();
    {
    "cursor" : "BtreeCursor a_1",
    "nscanned" : 2,
    "nscannedObjects" : 2,
    "n" : 2,
    "millis" : 0,
    "nYields" : 0,
    "nChunkSkips" : 0,
    "isMultiKey" : false,
    "indexOnly" : false,
    "indexBounds" : {
        "a" : [
            [
                {
                    "$minElement" : 1
                },
                {
                    "$maxElement" : 1
                }
            ]
        ]
    }
    }
    

提交回复
热议问题