top of page

Import and Analyze Data from MongoDB

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

To run this example, you must first install the Database Toolbox interface for MongoDB. For details, see Database Toolbox Interface for MongoDB Installation.

Create a MongoDB connection to the database mongotest. Here, the database server dbtb01 hosts this database using port number 27017.

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

conn =     
    mongo with properties:                 
        Database: 'mongotest'                
        UserName: ''                  
        Server: {'dbtb01'}                    
        Port: 27017         
        CollectionNames: {'airlinesmall', 'employee', 'largedata' 
                                                    ... and 3 more}          
        TotalDocuments: 23485919

conn is the mongo 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 six document collections. The first three collection names are airlinesmall, employee, and largedata.

  • This database contains 23,485,919 documents.

Verify the MongoDB connection.

ans =    

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

Specify the employee collection for document retrieval. Retrieve all documents in the collection by using the MongoDB connection. documents is a structure array.

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

Using all documents, determine the unique department names. deplist contains a cell array of character vectors for the department names. The employee collection contains seven departments.

departments = {documents(:).department}; 
deplist = unique(departments)'
deplist =    
    7×1 cell array      
        {'Application Engineering'}     
        {'Consulting'             }     
        {'Development'            }     
        {'Marketing'              }     
        {'Sales'                  }     
        {'Support'                }     
        {'Training'               }

Determine the maximum salary among all employees.

salaries = [documents(:).salary]; 
ans =        

Close the MongoDB connection.


Source: MathWorks

The Tech Platform



bottom of page