Docs HomeMongoDB for VS Code

Create Databases and Collections创建数据库和集合

You can create databases and collections using a MongoDB Playground.您可以使用MongoDB Playground创建数据库和集合

Prerequisites先决条件

If you have not done so already, you must complete the following prerequisites before you can create a database or collection with a MongoDB Playground:如果您还没有这样做,您必须完成以下先决条件,然后才能使用MongoDB Playground创建数据库或集合:

Create a Database and Collection创建数据库和集合

Once you connect to your deployment using MongoDB for VS code, use the left navigation to:使用MongoDB for VS Code连接到部署后,使用左侧导航:

  1. Select an active connection and click the icon that appears.选择一个活动连接,然后单击出现的图标。
  2. A MongoDB playground automatically opens with a template form to create a database and a regular collection or a time series collection.MongoDB演练场会自动打开一个模板表单,创建一个数据库和一个常规集合或一个时间序列集合
  3. Fill in const database and const collection with names of your database and collection.用数据库和集合的名称填充const databaseconst collection
  4. Uncomment the form of the collection you wish to create.取消注释要创建的集合的形式。
  5. Fill in the collection fields according to your collection's specifications.根据集合的规范填写集合字段。
  6. To run the playground, click the Play Button at the top right of the VS code navigation bar.要运行演练场,请单击VS Code导航栏右上角的“播放”按钮。

After running the playground, the left navigation updates with new database listed under the active connection it was created. 运行完演练场后,左侧导航将更新为在创建的活动连接下列出的新数据库。You can find the newly created collection by expanding the new database.您可以通过展开新数据库来查找新创建的集合。

Tip

See also: 另请参阅:

Example实例

This example creates a database named grades and a regular collection named testscores.本例创建了一个名为grades的数据库和一个命名为testscores的常规集合。

To use this example, start with a template from your MongoDB Playgrounds:要使用此示例,请从MongoDB Playgrounds中的模板开始:

const database = 'grades';
const collection = 'testscores';

use(database);

db.createCollection(collection);

In the example:在示例中:

  • const database declares the name grades for the database.声明数据库的名称grades
  • const collection declares the name testscores for the collection.声明集合的名称testscores
  • use(database) creates the new grades database.创建新的grades数据库。
  • db.createCollection(collection) creates the collection testscores inside of the grades database.grades数据库中创建集合testscores

When you press the Play Button, MongoDB for VS Code shows the following results in the Playground Results.json pane to confirm the creation of the database and collection.当您按下“播放”按钮时,MongoDB for VS Code会在Playground Results.json窗格中显示以下结果,以确认数据库和集合的创建。

{
"ok": 1
}

The grades database and testscores collection also appear in your left navigation:grades数据库和testscores成绩集合也显示在左侧导航中:

Image showing database and collection