This is machine translation

Translated by Microsoft
Mouseover text to see original. Click the button below to return to the English version of the page.

Note: This page has been translated by MathWorks. Click here to see
To view all translated materials including this page, select Country from the country navigator on the bottom of this page.


Create MongoDB collection





createCollection(conn,collection) creates a collection in MongoDB® by using the MongoDB connection.


collapse all

Connect to MongoDB and create a collection.

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, and largedata.

  • This database contains 23,485,919 documents.

Verify the MongoDB connection.

ans =



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

Create a collection in the database using the MongoDB connection. Specify the collection name taxidata.

collection = "taxidata";

Display the collections in the database by using the CollectionNames property. The database contains the new collection taxidata.

ans =

  1×7 cell array

  Columns 1 through 5

    {'airlinesmall'}    {'employee'}    {'largedata'}    {'nyctaxi'}    {'product'}

  Columns 6 through 7

    {'restaurants'}    {'taxidata'}

Close the MongoDB connection.


Input Arguments

collapse all

MongoDB connection, specified as a mongo object.

Collection name, specified as a string scalar.

Example: "taxidata"

Data Types: string

Introduced in R2017b