- Newest
- Most votes
- Most comments
There are a few key differences in how Amazon DocumentDB handles sparse and partial indexes compared to MongoDB that are causing your issues.
For sparse indexes in Amazon DocumentDB, you must explicitly include the $exists clause in your query for the index to be used. Try modifying your query for the lastEventAt field like this:
db.entries.find({ 'lastEventAt': { $exists: true, $gt: ISODate("2025-01-02") } }).explain()
For partial indexes, there's a case sensitivity issue in your query. Your index is on gc.idHash but your query is using gc.IdHash (note the capital 'I'). Field names in DocumentDB are case-sensitive, so this mismatch is causing the index to be ignored. Correct your query to:
db.entries.find({ 'gc.idHash': "foo" }).explain()
Additionally, for the partial index to be used, your query predicate must exactly match or be a logical subset of the partialFilterExpression. Since your partial index has a filter expression of { 'gc.idHash': { '$exists': true } }, you should include this in your query:
db.entries.find({ 'gc.idHash': { $exists: true, $eq: "foo" } }).explain()
The reason your unique constraints are being enforced during inserts but not used for queries is that DocumentDB separates the uniqueness constraint enforcement from the index usage in query optimization.
These adjustments should help your queries utilize the indexes properly in Amazon DocumentDB.
Sources
Functional differences: Amazon DocumentDB and MongoDB - Amazon DocumentDB
Partial index - Amazon DocumentDB
Modifying query to $and: [ { foo: { $exists: true }}, <original condition> ] solves the issue, thanks!
This requirement is NOT clearly stated in the documentation (https://docs.aws.amazon.com/documentdb/latest/developerguide/partial-index.html#partial-index-query), neither is mentioned in the Functional differences: Amazon DocumentDB and MongoDB - only sparse indices are being mentioned - I suggest that you state this it very clearly also for partial indices, because I'm surely not the first, not the last one that is going to bitten by this odd behaviour.
answered a year ago
Relevant content
asked 7 years ago
asked 3 years ago
- AWS OFFICIALUpdated 8 months ago
