0

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?

1 Answer 1

2

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 } )
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.