Improve querying fields exist in MongoDB

前端 未结 4 425
挽巷
挽巷 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-05 20:42

    Simply redesign your schema such that it's an indexable query. Your use case is infact analogous to the first example application given in MongoDB The Definitive Guide.

    If you want/need the convenience of result.a just store the keys somewhere indexable.

    instead of the existing:

    db.ent.insert({a:5775, b:'b1'})
    

    do

    db.ent.insert({a:5775, b:'b1', index: ['a', 'b']})
    

    That's then an indexable query:

    db.end.find({index: "a"}).explain()
    {
        "cursor" : "BtreeCursor index_1",
        "nscanned" : 1,
        "nscannedObjects" : 1,
        "n" : 1,
        "millis" : 0,
        "nYields" : 0,
        "nChunkSkips" : 0,
        "isMultiKey" : true,
        "indexOnly" : false,
        "indexBounds" : {
            "index" : [
                [
                    "a",
                    "a"
                ]
            ]
        }
    }
    

    or if you're ever likely to query also by value:

    db.ent.insert({
        a:5775, 
        b:'b1', 
        index: [
            {name: 'a', value: 5775}, 
            {name: 'b', value: 'b1'}
        ]
    })
    

    That's also an indexable query:

    db.end.find({"index.name": "a"}).explain()
    {
        "cursor" : "BtreeCursor index.name_",
        "nscanned" : 1,
        "nscannedObjects" : 1,
        "n" : 1,
        "millis" : 0,
        "nYields" : 0,
        "nChunkSkips" : 0,
        "isMultiKey" : true,
        "indexOnly" : false,
        "indexBounds" : {
            "index.name" : [
                [
                    "a",
                    "a"
                ]
            ]
        }
    }
    

提交回复
热议问题