Node.js MongoDB 创建集合
在 MongoDB 中,集合相当于 MySQL 中的表
创建集合
要在 MongoDB 中创建集合,请使用 createCollection()
方法
示例
创建一个名为“customers”的集合
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://:27017/";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("mydb");
dbo.createCollection("customers", function(err, res) {
if (err) throw err;
console.log("Collection created!");
db.close();
});
});
运行示例 »
将上面的代码保存在一个名为“demo_mongodb_createcollection.js”的文件中,然后运行该文件
运行“demo_mongodb_createcollection.js”
C:\Users\你的名字>node demo_mongodb_createcollection.js
这将产生以下结果:
Collection created!
重要提示:在 MongoDB 中,在集合包含内容之前,它不会被创建!
MongoDB 会等到您插入文档后,才会真正创建集合。