createIndex method

Future<Map<String, dynamic>> createIndex({
  1. String? key,
  2. Map<String, dynamic>? keys,
  3. bool? unique,
  4. bool? sparse,
  5. bool? background,
  6. bool? dropDups,
  7. Map<String, dynamic>? partialFilterExpression,
  8. String? name,
  9. bool? modernReply,
  10. Map? collation,
})

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 to keys)
  • keys - Map of field names and index direction (1 for ascending, -1 for descending)
  • unique - Whether the index should enforce uniqueness
  • sparse - Whether to create a sparse index (ignores null values)
  • background - Whether to build the index in the background
  • dropDups - Whether to drop duplicate documents during index creation
  • partialFilterExpression - Filter expression for partial indexes
  • name - Custom name for the index
  • modernReply - Whether to use modern reply format
  • collation - 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();
}