title | description | author | ms.author | ms.service | ms.subservice | ms.devlang | ms.topic | ms.date | ms.custom |
---|---|---|---|---|---|---|---|---|---|
Create a collection in Azure Cosmos DB for MongoDB using JavaScript |
Learn how to work with a collection in your Azure Cosmos DB for MongoDB database using the JavaScript SDK. |
gahl-levy |
gahllevy |
azure-cosmos-db |
mongodb |
javascript |
how-to |
06/23/2022 |
devx-track-js, devguide-js, cosmos-db-dev-journey |
[!INCLUDEMongoDB]
Manage your MongoDB collection stored in Azure Cosmos DB with the native MongoDB client driver.
Note
The example code snippets are available on GitHub as a JavaScript project.
API for MongoDB reference documentation | MongoDB Package (npm)
In Azure Cosmos DB, a collection is analogous to a table in a relational database. When you create a collection, the collection name forms a segment of the URI used to access the collection resource and any child docs.
Use an instance of the Collection class to access the collection on the server.
The following code snippets assume you've already created your client connection and that you close your client connection after these code snippets.
To create a collection, insert a document into the collection.
:::code language="javascript" source="~/samples-cosmosdb-mongodb-javascript/203-insert-doc/index.js" id="database_object":::
Drop the collection from the database to remove it permanently. However, the next insert or update operation that accesses the collection will create a new collection with that name.
:::code language="javascript" source="~/samples-cosmosdb-mongodb-javascript/299-drop-collection/index.js" id="drop_collection":::
The preceding code snippet displays the following example console output:
:::code language="console" source="~/samples-cosmosdb-mongodb-javascript/299-drop-collection/index.js" id="console_result":::
An index is used by the MongoDB query engine to improve performance to database queries.
:::code language="javascript" source="~/samples-cosmosdb-mongodb-javascript/225-get-collection-indexes/index.js" id="collection":::
The preceding code snippet displays the following example console output:
:::code language="console" source="~/samples-cosmosdb-mongodb-javascript/225-get-collection-indexes/index.js" id="console_result":::