Node.js - MongoDB 创建集合
MongoDB 数据库由一个或多个 Collection 组成。Collection 是一组 document 对象。一旦在 MongoDB 服务器上创建了数据库(独立服务器或 MongoDB Atlas 中的共享集群),就可以在其内部创建 Collection。Node.js 的 mongodb driver 提供了一个 createCollection() 方法,该方法返回一个 Collection 对象。
MongoDB 中的 Collection 类似于关系型数据库中的 table。但是,它没有预定义的 schema。集合中的每个 document 可以包含可变数量的 key-value 对,且每个 document 中的键不一定相同。
要创建 collection,请从数据库连接中获取数据库对象,然后调用 createCollection() 方法。
db.createCollection(name: string, options)
要创建的 collection 的名称作为参数传递。该方法返回一个 Promise。Collection 命名空间验证在服务器端执行。
const dbobj = await client.db(dbname);
const collection = await dbobj.createCollection("MyCollection");
请注意,即使在插入之前没有创建 collection,当您向其中插入 document 时,collection 也会被隐式创建。
const result = await client.db("mydatabase").collection("newcollection").insertOne({k1:v1, k2:v2});
示例
以下 Node.js 代码在名为 mydatabase 的 MongoDB 数据库中创建一个名为 MyCollection 的 Collection。
const {MongoClient} = require('mongodb');
async function main(){
const uri = "mongodb://localhost:27017/";
const client = new MongoClient(uri);
try {
// 连接到 MongoDB 集群
await client.connect();
await newcollection(client, "mydatabase");
} finally {
// 关闭与 MongoDB 集群的连接
await client.close();
}
}
main().catch(console.error);
async function newcollection (client, dbname){
const dbobj = await client.db(dbname);
const collection = await dbobj.createCollection("MyCollection");
console.log("Collection created");
console.log(collection);
}
MongoDB Compass 显示 MyCollection 已创建在 mydatabase 中。
您也可以在 MongoDB shell 中验证相同结果。
> use mydatabase < switched to db mydatabase > show collections < MyCollection