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") }

2 Answers 2

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

1
  • 1
    when should i use 1 rather than -1? Jan 12, 2022 at 14:58
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.