Main Content

Import and Analyze Data from MongoDB Using MongoDB C++ Interface

This example shows how to import employee data from a collection in MongoDB® into the MATLAB® workspace using the MongoDB C++ interface. The example then shows how to conduct a simple data analysis based on the imported data.

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: [14×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 14 document collections.

Verify the MongoDB connection.

isopen(conn)
ans = logical
   1

The database connection is successful because the isopen function returns 1. Otherwise, the database connection is closed.

Specify the employees collection for document retrieval. Retrieve all documents in the collection by using the MongoDB C++ interface connection. documents is a structure array.

collection = "employees";
documents = find(conn,collection);

Using all documents, determine the maximum salary of all employees. salaries contains an array of doubles for the salaries.

salaries = [];
for i = 1:length(documents)
    salaries = [salaries documents{i}.salary];
end
max(salaries)
ans = int32
    29000

Close the MongoDB connection.

close(conn)

See Also

| | | |

External Websites