12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
ADADADADAD
建站问答 时间:2024-11-30 20:00:48
作者:文/会员上传
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
在 MongoDB 中创建集合并写入数据库可以使用 insertOne() 或 insertMany() 方法。以下是使用 insertOne() 方法创建集合并写入数据的示例:首先,连接到 MongoDB 数据库:const Mo
以下为本文的正文内容,内容仅供参考!本站为公益性网站,复制本文以及下载DOC文档全部免费。
在 MongoDB 中创建集合并写入数据库可以使用 insertOne()
或 insertMany()
方法。
以下是使用 insertOne()
方法创建集合并写入数据的示例:
const MongoClient = require('mongodb').MongoClient;const url = 'mongodb://localhost:27017/mydb';MongoClient.connect(url, function(err, db) {if (err) throw err;console.log('数据库已连接');// 在这里执行创建集合和写入数据的操作});
db.createCollection('mycollection', function(err, res) {if (err) throw err;console.log('集合已创建');});
const collection = db.collection('mycollection');const data = { name: 'John', age: 30 };collection.insertOne(data, function(err, res) {if (err) throw err;console.log('文档已插入');db.close();});
如果要一次插入多个文档,可以使用 insertMany()
方法。示例代码如下:
const data = [{ name: 'John', age: 30 },{ name: 'Jane', age: 25 },{ name: 'Tom', age: 35 }];collection.insertMany(data, function(err, res) {if (err) throw err;console.log(`${res.insertedCount} 个文档已插入`);db.close();});
在执行完所有操作后,使用 db.close()
方法关闭数据库连接。
11-20
11-19
11-20
11-20
11-20
11-19
11-20
11-20
11-19
11-20
11-19
11-19
11-19
11-19
11-19
11-19