Import Filtered Data fromMongoDB
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, seeDatabase Toolbox Interface for MongoDB Installation.
Create a MongoDB connection to the databasemongotest
. Here, the database serverdbtb01
hosts this database using port number27017
.
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 themongo
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 theisopen
function returns1
. Otherwise, the database connection is closed.
Specify theairlinesmall
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
- MATLAB数据MongoD出口B
- Database Toolbox Interface for MongoDB Error Messages