在MongoDB中,可以通过插入多个文档来新建多个文档。可以使用insertMany()方法将多个文档插入到集合中。
以下是新建多个文档的步骤:
确保已经连接到MongoDB数据库。
选择要插入文档的集合。
创建多个文档的数组,每个文档是一个Javascript对象。
使用insertMany()方法将文档插入到集合中。
以下是一个示例代码:
//连接到MongoDB数据库const MongoClient = require('mongodb').MongoClient;const url = 'mongodb://localhost:27017';const dbName = 'mydatabase';MongoClient.connect(url, function(err, client) {if (err) throw err;console.log('Connected to MongoDB');const db = client.db(dbName);const collection = db.collection('mycollection');//创建多个文档的数组const documents = [{ name: 'John', age: 25 },{ name: 'Jane', age: 30 },{ name: 'Bob', age: 35 }];//插入多个文档到集合中collection.insertMany(documents, function(err, result) {if (err) throw err;console.log(result.insertedCount + ' documents inserted');client.close();});});在上面的示例中,我们使用insertMany()方法将一个包含三个文档的数组插入到名为’mycollection’的集合中。在插入完成后,可以通过result.insertedCount获取成功插入的文档数量。

