Main Content

Import Filtered Data from MongoDB Using MongoDB C++ Interface

This example shows how to import flight data from a MongoDB® collection into the MATLAB® workspace using the MongoDB C++ interface. The example then shows how to use a MongoDB query with filter criteria and a field list, and how to perform a simple data analysis based on the filtered flight 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.

ans = logical

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

Specify the airlinesmall collection. Define the MongoDB query to filter the flight data for the years 1998 through 1999. Specify the fields to retrieve from the collection.

collection = "airlinesmall";
mongoquery = "{""Year"":{""$gte"":1998,""$lt"":2000}}";
fields = strcat("{""Year"":1.0,""Month"":1.0,""DayofMonth"":1.0,""DayOfWeek"":1.0,", ...

Retrieve flight data using the MongoDB connection. documents is a structure array with fields that correspond to the specified fields.

documents = find(conn,collection,Query=mongoquery,Projection=fields)
documents=10911×1 struct array with fields:

Determine the unique years in the data.

years = [documents(:).Year];
ans = 1×2 int32 row vector

   1998   1999

Close the MongoDB connection.


See Also

| | | | |

External Websites