Main Content

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 = connection with properties:
           Database: "mongotest"
           UserName: ""
             Server: "dbtb01"
               Port: 27017
    CollectionNames: [13×1 string]

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.

ans = logical

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";

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

n = insert(conn,tsunamicoll,tsunamidata)
n = int64

Count Documents in Collection

Count the number of documents in the new collection.

ntsunamis = count(conn,tsunamicoll)
ntsunamis = int64

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,"{}")
ntsunamis = int64

Drop the collection from the mongotest database.


Close MongoDB C++ Interface Connection


See Also

| | | | | | | |

External Websites