In MongoDB, I have documents that look like
{
_id: 1,
name: "foo",
tags: ['someTag', 'someOtherTag'],
}
The large majority of my documents have no tags, so their tags field is set as tags: []
, but I need to frequently access the ones that do have tags.
I want to use a partial index here because it would create a much smaller index than if I just created an index on { tags: 1 }
, but the best way I could come up with was to do
db.myThings.createIndex({ tags: 1 },
{ partialFilterExpression: { "tags.0": { $exists: true } } } });
Which works, in that when I do db.myThings.stats(), it shows it created a much smaller index, but in order to use the index I now need to query by
db.myThings.find({ "tags.0": { $exists: true }, tags: "someTag" })
If I don't include the "tags.0": { $exists: true }
in my query, mongo will not use the index.
I know I could create a partial index based on the existence of the tags field itself, but I also want to be able to modify the array with $pull
updates, which wouldn't automatically remove the array from the document when pulling the last element.
Is there a better way to do this, where I wouldn't need to always remember to include the "tags.0": { $exists: true }
in all of my queries where I want to use the partial index?