I have the following mongoose schema:
var dataSchema = new Schema({
owner: { type: Schema.ObjectId, ref: 'User' },
time : { type: Date, default: Date.now },
eventCount:Number
});
For some dataObjects the eventCount is defined and a positive number, for other dataObjects the eventCount is undefined. I want to design an index such that queries like this are as fast as possible:
db.datacollection.find({owner: <some ID>, eventCount: {$exists:true}, time: {<some time range>})
What is the best way to do this?
Here is the best solution that I could think of but I'd be interested in knowing if anyone has a better solution:
Add an isEventCount boolean variable to the dataSchema. Set up mongoose middleware so that isEventCount is calculated before saving the object to db with the following logic.
if(eventCount > 0) {
isEventCount = true;
} else {
isEventCount = false;
}
then building an index like this
db.datacollection.ensureIndex({user:1, isEventCount: 1, time:1})
and running my query like this
db.datacollection.find({owner: <some ID>, isEventCount: true, time: {<some time range>})
There are a couple drawbacks to this approach. Namely:
- I am saving redundant information in the database.
- I have to write additional middleware code to achieve this.
- I have to modify existing entries in the db.
Is anyone aware of either a better solution or a library that can help with this?