溫馨提示×

mongodb怎么新建多個文檔

小億
106
2023-08-31 11:46:58
欄目: 云計算

在MongoDB中,可以通過插入多個文檔來新建多個文檔??梢允褂胕nsertMany()方法將多個文檔插入到集合中。

以下是新建多個文檔的步驟:

  1. 確保已經(jīng)連接到MongoDB數(shù)據(jù)庫。

  2. 選擇要插入文檔的集合。

  3. 創(chuàng)建多個文檔的數(shù)組,每個文檔是一個Javascript對象。

  4. 使用insertMany()方法將文檔插入到集合中。

以下是一個示例代碼:

//連接到MongoDB數(shù)據(jù)庫
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');
//創(chuàng)建多個文檔的數(shù)組
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()方法將一個包含三個文檔的數(shù)組插入到名為’mycollection’的集合中。在插入完成后,可以通過result.insertedCount獲取成功插入的文檔數(shù)量。

0