Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "value 1" of parameter of mongodb's "createIndex" mean?

Tags:

mongodb

I would like to create primary key for a mongodb collection, and when reading tutorials, the following thing is always not explained.

What does value of parameter of mongodb's "createIndex" mean?

For example, in

https://www.sitepoint.com/7-simple-speed-solutions-mongodb/

Indexes are created with createIndex. The most basic command to index the country field in the user collection in ascending order:

db.user.createIndex({ country: 1 });

The majority of your indexes are likely to be single fields, but you can also create compound indexes on two or more fields. For example:

db.user.createIndex({ country: 1, city: 1 });

I don't understand what do the values 1 mean. "db.someCollection.createIndex({someField:1})" can be found every where, but what the 1 values mean is never explained.

What does the 1 values mean in mongodb's createIndex for a collection? Can it be 2 or 3 or -1?

like image 818
Tom Avatar asked Dec 07 '25 06:12

Tom


2 Answers

The number 1 means in ascending order. A -1 would index the collection in descending order. This does not impact queries where you receive single documents. The direction is not relevant when you sort multiple documents as mongodb can traverse an index in both directions.

The order is relevant when you use compound keys. See the official docs for sort order in compund indexes: https://docs.mongodb.com/manual/core/index-compound/#sort-order

like image 87
mbuechmann Avatar answered Dec 10 '25 03:12

mbuechmann


According to MongoDB docs:

For an ascending index on a field, specify a value of 1; for descending index, specify a value of -1.

like image 41
Héctor Avatar answered Dec 10 '25 04:12

Héctor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!