Import Filtered Data from MongoDB
This example shows how to import flight data from a MongoDB® collection into the MATLAB® workspace using the Database Toolbox™ interface for MongoDB. 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.
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
, andlargedata
.This database contains 23,485,919 documents.
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 airlinesmall
collection. Define the MongoDB query to filter the flight data for the years 1998 through 1999.
Specify fields to retrieve from the collection.
collection = "airlinesmall"; mongoquery = '{"Year":{$gte:1998,$lt:2000}}'; fields = ['{"Year":1.0,"Month":1.0,"DayofMonth":1.0,"DayOfWeek":1.0,' ... '"DepTime":1.0,"ArrTime":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: x_id Year Month DayofMonth DayOfWeek DepTime ArrTime
Determine the unique years in the data.
years = [documents(:).Year]; unique(years)
ans = 1998 1999
Close the MongoDB connection.
close(conn)
See Also
mongo
| isopen
| close
| find
| unique
Related Topics
- Import and Analyze Data from MongoDB
- Import Large Data from MongoDB
- Export MATLAB Data into MongoDB
- Database Toolbox Interface for MongoDB Error Messages