10

How do I create an indexes for "date"?

CentOS7, MongoDB server version: 3.4.2

db.animals.createIndex('date')
{
    "ok" : 0,
    "errmsg" : "The field 'key' must be an object, but got string",
    "code" : 14,
    "codeName" : "TypeMismatch"
}

db.animals.find({}, {date: 1}).limit(1)
{ "_id" : 3477, "date" : ISODate("2016-12-22T09:38:59Z") }
まめたろう
  • 281
  • 1
  • 2
  • 10

2 Answers2

42

You can create simple index on key date using:

Ascending order: db.animals.createIndex({'date':1})

Descending order: db.animals.createIndex({'date':-1})

You may need to take a look at indexing doc before adding indexes

Atish
  • 4,277
  • 2
  • 24
  • 32
8

for single field you don't need to reverse the index as mongodb can use the index in either direction. It should only matter when you have a compound index and you have a sort going in different directions.

Dwayne Mcnab
  • 131
  • 1
  • 1