MongoDB count partially indexed items

334 Views Asked by At

I have a partial index on a collection that looks sorta like this:

{ // Fields
    "Name" : 1
}
{ // Options
    "unique" : true,
    "name" : "Name_1",
    "partialFilterExpression" : {
        "IsArchived" : {
            "$eq" : true
        }
    }
}

I just want to get a count of the number of items that have been indexed by this partial index, just to check if it's working. Is there a way to do that? Or is there another good way to check what all is indexed by a partial index?

2

There are 2 best solutions below

1
On BEST ANSWER

MongoDB does not support inspecting the contents of an index in the sense of getting details on the indexed documents.

You can, however, simply run a query against your collection using the same filter as the one in your index in order to get the indexed documents:

db.collection.find({ "IsArchived": { "$eq": true } })

Also, you can add .count() at the end if you want to get the count:

db.collection.find({ "IsArchived": { "$eq": true } }).count()

In order to see if your index gets used you could run e.g. the following query:

db.collection.find({ "Name": "index check", "IsArchived": true }).explain()

If the index gets used (which should be the case) then issuing the above statement should print something like this somewhere inside the "winningPlan" field:

"inputStage" : {
    "stage" : "IXSCAN",
    "keyPattern" : {
        "Name" : "index check"
    },
    "indexName" : "<your index name>"

If it prints something like this then the index does not get used:

    "winningPlan" : {
        "stage" : "COLLSCAN",
0
On

I just realized I was being a bit thick. Because I am using the "unique" flag, I could also test the index by just inserting items into the collection that had the same name. In other words, for the index:

{ // Note: using IsArchived: false instead of true
    "unique" : true,
    "name" : "Name_1",
    "partialFilterExpression" : {
        "IsArchived" : {
            "$eq" : false
        }
    }
}

I should get the following results for inserting these items:

{ // Success
    "Name" : "test1",
    "IsArchived" : false
}

{ // Failure
    "Name" : "test1",
    "IsArchived" : false
}

{ // Success
    "Name" : "test1",
    "IsArchived" : true
}