How does MongoDB index arrays?

后端 未结 2 1238
春和景丽
春和景丽 2021-01-30 07:59

In MongoDB, if I were to store an array (say [\"red\", \"blue\"]) in a field \"color\", does it index \"red\" and \"blue\" so

2条回答
  •  北荒
    北荒 (楼主)
    2021-01-30 08:59

    You can simply test index usage by appending "explain" to your query:

    > db.col1.save({'colors': ['red','blue']})
    
    # without index
    > db.col1.find({'colors': 'red'}).explain()
    {
            "queryPlanner" : {
                    "plannerVersion" : 1,
                    "namespace" : "protrain.col1",
                    "indexFilterSet" : false,
                    "parsedQuery" : {
                            "colors" : {
                                    "$eq" : "red"
                            }
                    },
                    "winningPlan" : {
                            "stage" : "COLLSCAN", <--- simple column scan
                            "filter" : {
                                    "colors" : {
                                            "$eq" : "red"
                                    }
                            },
                            "direction" : "forward"
                    },
                    "rejectedPlans" : [ ]
            },
            "serverInfo" : {
                    "host" : "bee34f15fe28",
                    "port" : 27017,
                    "version" : "3.4.4",
                    "gitVersion" : "888390515874a9debd1b6c5d36559ca86b44babd"
            },
            "ok" : 1
    }
    
    # query with index
    > db.col1.createIndex( { "colors":1 } )
    > db.col1.find({'colors': 'red'}).explain()
    {
            "queryPlanner" : {
                    "plannerVersion" : 1,
                    "namespace" : "protrain.col1",
                    "indexFilterSet" : false,
                    "parsedQuery" : {
                            "colors" : {
                                    "$eq" : "red"
                            }
                    },
                    "winningPlan" : {
                            "stage" : "FETCH",
                            "inputStage" : {
                                    "stage" : "IXSCAN", 
         
     
    热议问题