Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create an indexes for "date"?

Tags:

mongodb

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") }
like image 594
まめたろう Avatar asked Mar 19 '17 14:03

まめたろう


People also ask

How do you CREATE INDEX?

CREATE UNIQUE INDEX SyntaxON table_name (column1, column2, ...); Note: The syntax for creating indexes varies among different databases. Therefore: Check the syntax for creating indexes in your database.

How do I index a date in python?

1 Answer. If you have a dataframe named 'df' with DatetimeIndex, the following command will add a column labeled 'Timestamp' and the values corresponding to the values of the index: df['Timestamp'] = df. index.

Should I index a date column?

Is it a good idea to have a index on the Timestamp column ? Yes, it is generally a good idea to have an index on a field used in a query criteria. This is really useful when there are a large number of documents (e.g., a million) in the collection. The index will be used to run the query fast.

How do I create an index in SQL?

If we want to create indexes for unique values in a column, we use the CREATE UNIQUE INDEX constraint. For example, -- create unique index CREATE UNIQUE INDEX college_index ON Colleges(college_code); Here, the SQL command creates a unique index named college_index on the Colleges table using the college_code column.


2 Answers

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

like image 197
Atish Avatar answered Nov 05 '22 19:11

Atish


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.

like image 25
Dwayne Mcnab Avatar answered Nov 05 '22 21:11

Dwayne Mcnab