Reputation: 26142
Let's say I have a emails
collection with fields and records like:
{
sendAt: "",
to: "[email protected]",
from: "[email protected]"
}
If I need to to query only records with empty sendAt
field. Considering this requirement how should I index this collection field? I don't actually need to query any specific dates in sendAt
field so full index will be redundant in my view. Is it possible to do with mondogb?
Upvotes: 0
Views: 609
Reputation: 858
Starting from MongoDb 3.2 you can use partial indexes: https://docs.mongodb.org/manual/core/index-partial.
For example, in your case:
db.emails.createIndex(
{ sendAt: 1 },
{ partialFilterExpression: { sendAt: "" } }
)
Another approach is to add extra field to documents where sendAt is empty and create a sparse index on that field: https://docs.mongodb.org/manual/core/index-sparse/
{
sendAt: "",
to: "[email protected]",
from: "[email protected]",
sendAtEmpty: true
}
{
sendAt: "1/1/1980",
to: "[email protected]",
from: "[email protected]",
}
db.emails.createIndex( { "sendAtEmpty": 1 }, { sparse: true } )
Upvotes: 2