%% Export MATLAB Data into MongoDB Using MongoDB C++ Interface
% This example shows how to export table and structure data from the MATLAB® workspace into new MongoDB® collections using the MongoDB C++ interface. The example then shows how to count the number of documents in the collections, remove documents from the collections, and drop the collections.
% The example uses the data set tsunamis.xlsx, which contains tsunami data. You can find this file in the toolbox/matlab/demos folder.
%
%% Create MongoDB C++ Interface Connection
% Create a MongoDB connection to the database mongotest using the MongoDB C++ interface. Here, the database server dbtb01 hosts this database using port number 27017.

server = "dbtb01";
port = 27017;
dbname = "mongotest";
conn = mongoc(server,port,dbname)

% conn is the connection object that contains the MongoDB connection. The object properties contain information about the connection and the database.
% The database name is mongotest.
% The user name is blank.
% The database server is dbtb01.
% The port number is 27017.
% This database contains 13 document collections.
%
% Verify the MongoDB connection.

isopen(conn)

% The database connection is successful because the isopen function returns 1. Otherwise, the database connection is closed.
%
%% Create Collection and Export Data into MongoDB
% Load the data set using the readtable function. Convert tsunami data to a structure using the table2struct function. The MATLAB workspace contains the tsunamidata structure.

data = readtable("tsunamis.xlsx");
tsunamidata = table2struct(data);

% Create a collection to store the tsunami data using the MongoDB connection.

tsunamicoll = "tsunamis";
createCollection(conn,tsunamicoll)

% Export structure data into the tsunamis collection. n contains the number of documents inserted.

n = insert(conn,tsunamicoll,tsunamidata)

%% Count Documents in Collection
% Count the number of documents in the new collection.

ntsunamis = count(conn,tsunamicoll)

%% Remove Documents and Drop Collection
% Remove all documents from the collection. ntsunamis contains the number of documents removed from the collection.

ntsunamis = remove(conn,tsunamicoll,"{}")

% Drop the collection from the mongotest database.

dropCollection(conn,tsunamicoll)

%
%% Close MongoDB C++ Interface Connection

close(conn)

% Copyright 2020 The MathWorks, Inc.