在 MongoDB
中,你可以使用 insertOne
或 insertMany
方法向集合中插入文档。以下是插入文档的基本步骤:
比如插入单个文档:
使用 insertOne
方法可以向集合中插入单个文档。
// 导入 MongoDB 驱动
const MongoClient = require('mongodb').MongoClient;
// 定义数据库连接字符串和数据库名称
const url = 'mongodb://localhost:27017';
const dbName = 'your_database';
// 创建 MongoClient 实例
const client = new MongoClient(url, { useNewUrlParser: true });
// 连接到 MongoDB 服务器
client.connect(function(err) {
if (err) throw err;
// 选择要插入文档的集合
const db = client.db(dbName);
const collection = db.collection('your_collection');
// 插入单个文档
collection.insertOne({
key1: 'value1',
key2: 'value2',
// 其他字段...
}, function(err, result) {
if (err) throw err;
console.log('插入的文档数量:', result.insertedCount);
// 关闭数据库连接
client.close();
});
});