MongoDB创建主键时,createIndex方法参数值(如1)的含义是什么?
createIndex() Parameters Hey there, let's break down what those parameters in MongoDB's createIndex() method mean, using your example of db.user.createIndex({ country: 1 }) as a starting point.
The Core Index Definition Object
The first argument you pass to createIndex() is an object that defines which fields to index and their sort direction:
- The keys in this object are the names of the fields you want to index (in your case,
country). - The values represent the sort direction of the index:
1= Ascending order: MongoDB stores index entries from the smallest to largest value of the field. This is perfect for queries where you need results sorted from low to high, or just want to speed up basic lookups on thecountryfield.-1= Descending order: Index entries are stored from largest to smallest value. Use this if you frequently run queries that need results sorted in reverse order for that field.
Optional Configuration Parameters
Beyond the basic index definition, you can pass a second optional object to createIndex() to tweak the index's behavior. Some common ones include:
unique: true: Creates a unique index, ensuring no two documents in the collection have the same value for the indexed field (great for fields likeemailwhere duplicates should be prevented). Example:db.user.createIndex({ email: 1 }, { unique: true })background: true: Builds the index in the background, so your database can continue handling other operations while the index is created (useful for large collections where you don't want to block traffic).sparse: true: Only includes documents that actually have the indexed field in the index, which saves storage space if many documents don't contain that field.
Your Example in Context
The command db.user.createIndex({ country: 1 }) creates a basic ascending single-field index on the country field of the user collection. Single-field indexes are the most common type in MongoDB because they drastically speed up queries that filter or sort by that one field—exactly the kind of optimization you saw referenced.
内容的提问来源于stack exchange,提问作者Tom

