MongoDB(17)如何在MongoDB中创建集合?

6 阅读3分钟

在MongoDB中,集合(Collection)是存储文档的容器。创建集合的过程是比较简单的,你可以通过MongoDB Shell或编程语言(如Node.js或Python)来完成。以下是详细的步骤和代码示例,展示如何在不同操作系统上创建集合。

使用MongoDB Shell创建集合

1. 启动MongoDB Shell

首先,打开终端或命令提示符,启动MongoDB Shell:

mongo

2. 选择数据库

在MongoDB Shell中选择你要创建集合的数据库。如果数据库不存在,MongoDB会自动创建一个新的数据库。

use myDatabase

3. 创建集合

使用 db.createCollection 方法创建一个新的集合。

db.createCollection("myNewCollection")

4. 验证集合创建

使用 show collections 命令验证集合是否创建成功。

show collections

使用Node.js创建集合

以下是使用Node.js和MongoDB驱动程序创建集合的示例代码。

1. 安装MongoDB Node.js驱动

在终端中运行以下命令来安装MongoDB的Node.js驱动:

npm install mongodb

2. 创建并运行Node.js脚本

创建一个新的Node.js脚本文件(如 createCollection.js)并添加以下代码:

const { MongoClient } = require('mongodb');

async function main() {
    const uri = "mongodb://localhost:27017";
    const client = new MongoClient(uri, { useUnifiedTopology: true });

    try {
        // 连接到MongoDB服务器
        await client.connect();
        console.log("Connected to MongoDB");

        // 选择数据库
        const db = client.db('myDatabase');

        // 创建集合
        await db.createCollection('myNewCollection');
        console.log('Collection created!');

        // 验证集合的创建
        const collections = await db.listCollections().toArray();
        console.log('Collections:', collections.map(c => c.name));

    } finally {
        // 关闭连接
        await client.close();
    }
}

main().catch(console.error);

运行这个脚本:

node createCollection.js

使用Python创建集合

以下是使用Python和PyMongo驱动程序创建集合的示例代码。

1. 安装PyMongo

在终端中运行以下命令来安装PyMongo:

pip install pymongo

2. 创建并运行Python脚本

创建一个新的Python脚本文件(如 create_collection.py)并添加以下代码:

from pymongo import MongoClient

def main():
    client = MongoClient('mongodb://localhost:27017/')

    # 选择数据库
    db = client['myDatabase']

    # 创建集合
    db.create_collection('myNewCollection')
    print('Collection created!')

    # 验证集合的创建
    collections = db.list_collection_names()
    print('Collections:', collections)

    # 关闭连接
    client.close()

if __name__ == '__main__':
    main()

运行这个脚本:

python create_collection.py

使用Java创建集合

以下是使用Java和MongoDB驱动程序创建集合的示例代码。

1. 添加MongoDB Java驱动依赖

如果你使用的是Maven项目,添加以下依赖到你的 pom.xml 文件中:

<dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>mongodb-driver-sync</artifactId>
    <version>4.4.0</version>
</dependency>

2. 创建Java类并添加代码

创建一个新的Java类文件(如 CreateCollection.java)并添加以下代码:

import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;

public class CreateCollection {
    public static void main(String[] args) {
        // 连接到MongoDB服务器
        MongoClient mongoClient = new MongoClient("localhost", 27017);

        // 选择数据库
        MongoDatabase database = mongoClient.getDatabase("myDatabase");

        // 创建集合
        database.createCollection("myNewCollection");
        System.out.println("Collection created!");

        // 验证集合的创建
        for (String name : database.listCollectionNames()) {
            System.out.println(name);
        }

        // 关闭连接
        mongoClient.close();
    }
}

编译并运行这个Java类:

javac -cp .:path/to/mongodb-driver-sync-4.4.0.jar CreateCollection.java
java -cp .:path/to/mongodb-driver-sync-4.4.0.jar CreateCollection

总结

在MongoDB中创建集合的步骤如下:

  1. 启动MongoDB Shell:使用 mongo 命令启动MongoDB Shell。
  2. 选择数据库:使用 use myDatabase 命令选择数据库。
  3. 创建集合:使用 db.createCollection("myNewCollection") 命令创建集合。
  4. 验证集合创建:使用 show collections 命令验证集合是否创建成功。

此外,还可以使用Node.js、Python和Java来编写脚本或程序来创建集合。以上步骤和代码示例可以帮助你在不同编程语言和操作系统上创建并验证MongoDB集合。