createIndex method
Creates a database index on the collection.
This method creates a new index on the MongoDB collection with the specified options. Indexes improve query performance and can enforce uniqueness constraints.
Parameters:
key
- Single field name to index (alternative tokeys
)keys
- Map of field names and index direction (1 for ascending, -1 for descending)unique
- Whether the index should enforce uniquenesssparse
- Whether to create a sparse index (ignores null values)background
- Whether to build the index in the backgrounddropDups
- Whether to drop duplicate documents during index creationpartialFilterExpression
- Filter expression for partial indexesname
- Custom name for the indexmodernReply
- Whether to use modern reply formatcollation
- Collation options for the index
Returns a map containing the result of the index creation operation.
Throws MongoDartError if the MongoDB server doesn't support OpMsg.
Throws ArgumentError if both key
and keys
are provided, or if neither is provided.
Example:
await collection.createIndex(
key: 'email',
unique: true,
sparse: true,
);
Implementation
Future<Map<String, dynamic>> createIndex({
String? key,
Map<String, dynamic>? keys,
bool? unique,
bool? sparse,
bool? background,
bool? dropDups,
Map<String, dynamic>? partialFilterExpression,
String? name,
bool? modernReply,
Map<dynamic, dynamic>? collation,
}) async {
if (!db.masterConnection.serverCapabilities.supportsOpMsg) {
throw MongoDartError('Use createIndex() method on db (before 3.6)');
}
modernReply ??= true;
var indexOptions = CreateIndexOptions(
collection,
uniqueIndex: unique == true,
sparseIndex: sparse == true,
background: background == true,
dropDuplicatedEntries: dropDups == true,
partialFilterExpression: partialFilterExpression,
indexName: name,
collation: collation,
);
var indexOperation =
CreateIndexOperation(db, collection, _setKeys(key, keys), indexOptions);
var res = await indexOperation.execute();
if (res[keyOk] == 0.0) {
// It should be better to create a MongoDartError,
// but, for compatibility reasons, we throw the received map.
throw res;
}
if (modernReply) {
return res;
}
return db.getLastError();
}