bulkWrite method

Future<BulkWriteResult> bulkWrite(
  1. List<Map<String, Object>> documents, {
  2. bool ordered = true,
  3. WriteConcern? writeConcern,
})

Implementation

Future<BulkWriteResult> bulkWrite(List<Map<String, Object>> documents,
    {bool ordered = true, WriteConcern? writeConcern}) async {
  Bulk bulk;
  if (ordered) {
    bulk = OrderedBulk(this, writeConcern: writeConcern);
  } else {
    bulk = UnorderedBulk(this, writeConcern: writeConcern);
  }
  var index = -1;
  for (var document in documents) {
    index++;
    if (document.isEmpty) {
      continue;
    }
    var key = document.keys.first;
    var testMap = document[key];
    if (testMap is! Map<String, Object>) {
      throw MongoDartError('The "$key" element at index '
          '$index must contain a Map');
    }
    var docMap = testMap;

    switch (key) {
      case bulkInsertOne:
        if (docMap[bulkDocument] is! Map<String, dynamic>) {
          throw MongoDartError('The "$bulkDocument" key of the '
              '"$bulkInsertOne" element at index $index must '
              'contain a Map');
        }
        bulk.insertOne(docMap[bulkDocument] as Map<String, dynamic>);

        break;
      case bulkInsertMany:
        if (docMap[bulkDocuments] is! List<Map<String, dynamic>>) {
          throw MongoDartError('The "$bulkDocuments" key of the '
              '"$bulkInsertMany" element at index $index must '
              'contain a List of Maps');
        }
        bulk.insertMany(docMap[bulkDocuments] as List<Map<String, dynamic>>);
        break;
      case bulkUpdateOne:
        bulk.updateOneFromMap(docMap, index: index);
        break;
      case bulkUpdateMany:
        bulk.updateManyFromMap(docMap, index: index);
        break;
      case bulkReplaceOne:
        bulk.replaceOneFromMap(docMap, index: index);
        break;
      case bulkDeleteOne:
        bulk.deleteOneFromMap(docMap, index: index);
        break;
      case bulkDeleteMany:
        bulk.deleteManyFromMap(docMap, index: index);
        break;
      default:
        throw StateError('The operation "$key" is not allowed in bulkWrite');
    }
  }

  return bulk.executeDocument();
}