阅读量:2
在MongoDB中,插入文档到集合(collection)的基本操作是使用insertOne()或insertMany()方法。这里分别介绍这两个方法的使用:
insertOne():此方法用于向集合中插入一个文档。
// 引入MongoDB客户端
const MongoClient = require('mongodb').MongoClient;
// 连接到MongoDB服务器
const url = 'mongodb://localhost:27017';
const dbName = 'myDatabase';
const client = new MongoClient(url, { useUnifiedTopology: true });
client.connect(err => {
if (err) throw err;
// 选择数据库和集合
const db = client.db(dbName);
const collection = db.collection('myCollection');
// 定义要插入的文档
const document = {
name: 'John Doe',
age: 30,
city: 'New York'
};
// 插入文档
collection.insertOne(document, (err, res) => {
if (err) throw err;
console.log('Document inserted:', res.ops[0]);
client.close();
});
});
insertMany():此方法用于向集合中插入多个文档。
// 引入MongoDB客户端
const MongoClient = require('mongodb').MongoClient;
// 连接到MongoDB服务器
const url = 'mongodb://localhost:27017';
const dbName = 'myDatabase';
const client = new MongoClient(url, { useUnifiedTopology: true });
client.connect(err => {
if (err) throw err;
// 选择数据库和集合
const db = client.db(dbName);
const collection = db.collection('myCollection');
// 定义要插入的文档数组
const documents = [
{ name: 'John Doe', age: 30, city: 'New York' },
{ name: 'Jane Doe', age: 28, city: 'San Francisco' },
{ name: 'Mike Smith', age: 35, city: 'Los Angeles' }
];
// 插入多个文档
collection.insertMany(documents, (err, res) => {
if (err) throw err;
console.log('Documents inserted:', res.ops);
client.close();
});
});
以上示例展示了如何在MongoDB中使用insertOne()和insertMany()方法插入文档。请确保已安装并运行了MongoDB服务器,并根据实际情况修改数据库连接字符串、数据库名称和集合名称。
以上就是关于“mongodb文档型数据库如何进行插入”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm