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.
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 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,", ... """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:
'58f7bd1e25f91a4580b86bc5' 1999 10 9 6 1329 1428
'58f7bd1e25f91a4580b86bc6' 1999 10 6 3 1447 1650
'58f7bd1e25f91a4580b86bc7' 1999 10 7 4 1329 1651
'58f7bd1e25f91a4580b86bc8' 1999 10 7 4 1435 1547
'58f7bd1e25f91a4580b86bc9' 1999 10 3 7 1345 1632
'58f7bd1e25f91a4580b86bca' 1999 10 7 4 1130 1205
'58f7bd1e25f91a4580b86bcb' 1999 10 19 2 1311 1423
'58f7bd1e25f91a4580b86bcc' 1999 10 7 4 1325 1431
'58f7bd1e25f91a4580b86bcd' 1999 10 29 5 1655 2026
'58f7bd1e25f91a4580b86bce' 1999 10 11 1 642 838
'58f7bd1e25f91a4580b86bcf' 1999 10 31 7 857 1121
'58f7bd1e25f91a4580b86bd0' 1999 10 7 4 1135 1400
'58f7bd1e25f91a4580b86bd1' 1999 10 24 7 605 833
'58f7bd1e25f91a4580b86bd2' 1999 10 28 4 1248 1337
Determine the unique years in the data.
years = [documents(:).Year]; unique(years)
ans = 1×2 int32 row vector
1998 1999
Close the MongoDB connection.
close(conn)
See Also
mongoc | isopen | find | close | strcat | unique