%% Retrieve Specific Fields in Collection
% Connect to MongoDB® using the MongoDB C++ interface and retrieve all documents in a collection. Specify the fields to retrieve for each document. Import the documents into MATLAB®. In this example, each document in the collection represents an employee.
%
% 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 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 13 document collections.
%
% Verify the MongoDB connection.

isopen(conn)

% The database connection is successful because the isopen function returns 1. Otherwise, the database connection is closed.
%
% Specify the employees collection for document retrieval. Specify the fields to retrieve for each document by using a string scalar that contains a JSON-style string. For this example, return the department_id and salary fields.

collection = "employees";
fields = "{""department_id"":1.0,""salary"":1.0}";

%
% Retrieve all documents in the collection. Use the name-value argument Projection to retrieve the specified fields for each document. documents is a cell array.

documents = find(conn,collection,Projection=fields);

%
% Display the first document in the results. In addition to the unique identifier for the document, the document contains only the specified fields.

documents{1}

%
% Close the MongoDB connection.

close(conn)

% Copyright 2020 The MathWorks, Inc.