25

Mongoose version >= 4.0 has a timestamps option which creates an updatedAt and createdAt field for schemas when timestamps is set to true.

http://mongoosejs.com/docs/guide.html#timestamps

Are the updatedAt and createdAt fields indexed?

Gianfranco P.
  • 10,049
  • 6
  • 51
  • 68
steampowered
  • 11,809
  • 12
  • 78
  • 98

1 Answers1

32

No they are not indexed, You have to do indexing by yourself, like any other field.

animalSchema.index({"createdAt": 1});
animalSchema.index({"updatedAt": 1});
enRaiser
  • 2,606
  • 2
  • 21
  • 39
  • 4
    Note to readers: the `1` means ascending order, not `true`. And `-1` means descending, for those who don't often make site-level mondodb indexes ([not clearly documented](http://mongoosejs.com/docs/guide.html#indexes) as of today). – steampowered Aug 16 '16 at 11:51
  • 2
    @steampowered and it shouldn't matter what sort order index has if it's not compound. – pronebird Jun 11 '18 at 09:54
  • 1
    @Andy good point. I think I was also searching for documentation on simple sorting though, which obviously does matter. – steampowered Jun 11 '18 at 15:16
  • 1
    For a [single-field](https://docs.mongodb.com/manual/indexes/#single-field) index and sort operations, the sort order (i.e. ascending or descending) of the index key does not matter because MongoDB can traverse the index in either direction. – Hatem Alimam Jul 06 '20 at 18:27
  • Do you need separate lines for that? Doesn't `animalSchema.index({"createdAt": 1, "updatedAt": 1 })` work? – Xavier Mukodi Aug 20 '23 at 10:47