Search code examples
node.jsmongodbmongodb-querynosqlmongodb-indexes

What if some documents don't have a field that is part of an index?


A collection has an indexed involved field_A. But field_A is not required. So what happens if some documents do not have this field? Will the index still work for documents that do have this field?


Solution

  • Yes it works, here is a test:

    db.collection.createIndex({ field_A: 1 });
    
    for (let i = 0; i < 100; i++)
       db.collection.insertOne({ field_B: i });
    
    db.collection.stats(1024).indexSizes
    
    { "_id_" : 20, "field_A_1" : 20 }
    

    You see index field_A_1 has a size of 20 kiByte. This behavior is different to most relational DBMS database where such index would have a size of zero.

    The index is also used by your query, if you use the field:

    db.collection.find({ field_B: 1 }).explain().queryPlanner.winningPlan;
    
    {
        "stage" : "COLLSCAN",
        "filter" : {
            "field_B" : {
                "$eq" : 1
            }
        }
    }
    
    db.collection.find({ field_A: null, field_B: 1 }).explain().queryPlanner.winningPlan;
    
    {
        "stage" : "FETCH",
        "inputStage" : {
            "stage" : "IXSCAN",
            "keyPattern" : {
                "field_A" : 1
            },
            "indexName" : "field_A_1",
            "indexBounds" : {
                "field_A" : [
                    "[undefined, undefined]",
                    "[null, null]"
                ]
            }
        }
    }