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,
})

This function is provided for all servers starting from version 3.6 For previous releases use the same method on Db class.

The modernReply flag allows the caller to receive the result of the command without a call to getLastError(). As the format is different from the getLastError() one, for compatibility reasons, if you specify false, the old format is returned (but one more getLastError() is performed). Example of the new format: {createdCollectionAutomatically: false, numIndexesBefore: 2, numIndexesAfter: 3, ok: 1.0}

Example of the old format: {"connectionId" -> 11, "n" -> 0, "syncMillis" -> 0, "writtenTo" -> null, "err" -> null, "ok" -> 1.0}

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}) async {
  if (!db.masterConnection.serverCapabilities.supportsOpMsg) {
    throw MongoDartError('Use createIndex() method on db (before 3.6)');
  }

  modernReply ??= true;
  var indexOptions = CreateIndexOptions(this,
      uniqueIndex: unique == true,
      sparseIndex: sparse == true,
      background: background == true,
      dropDuplicatedEntries: dropDups == true,
      partialFilterExpression: partialFilterExpression,
      indexName: name);

  var indexOperation =
      CreateIndexOperation(db, this, _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();
}