I would like to speed up an query on my mongoDB which uses $where to compare two fields in the document, which seems to be really slow.
My query look like this:
db.mycollection.find({ $where : "this.lastCheckDate < this.modificationDate})
What I would like to do is add a field to my document, i.e. isCheckDateLowerThenModDate, on which I could execute a probably much faster query:
db.mycollection.find({"isCheckDateLowerThenModDate":true})
I quite new to mongoDB an have no idea how to do this. I would appreciate if someone could give me some hints or examples on
- How to initialize such a field on an existing collection
- How to maintain this field. Which means how to update this field when
lastCheckDateormodificationDatechanges.
Thanks in advance for your help!
You are thinking in a right way!
Most simple way is to load each document (from your language), calculate this field, update and save.
Or you could perform an update via mongo shell:
You have to do it yourself from your client code. Make some wrapper for update, save operations and recalculate this value each time there. To be absolutely sure that this update works — write unit tests.