MongoDB: 一括挿入 (Bulk.insert) と複数挿入 (insert([…]))
MongoDB では、バッチインサートとマルチインサートという 2 つの方法で複数のドキュメントを挿入できます。
1回の操作で複数のドキュメントを挿入するために、 `Bulk.insert` メソッドを使用できます。以下はバッチ挿入を行うためのサンプル・コードです。
const MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017', function(err, client) {
if (err) throw err;
const db = client.db('mydb');
const collection = db.collection('mycollection');
const documents = [
{ name: 'John', age: 30 },
{ name: 'Jane', age: 25 },
{ name: 'Bob', age: 35 }
];
collection.bulkWrite(documents.map(doc => ({
insertOne: { document: doc }
})), function(err, result) {
if (err) throw err;
console.log('Documents inserted:', result.insertedCount);
client.close();
});
});
insertメソッドで挿入を複数行いドキュメントを配列で挿入します。以下にまとめて挿入する方法を示すサンプルコードを示します。
const MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017', function(err, client) {
if (err) throw err;
const db = client.db('mydb');
const collection = db.collection('mycollection');
const documents = [
{ name: 'John', age: 30 },
{ name: 'Jane', age: 25 },
{ name: 'Bob', age: 35 }
];
collection.insert(documents, function(err, result) {
if (err) throw err;
console.log('Documents inserted:', result.insertedCount);
client.close();
});
});
一括挿入と複数挿入のいずれも、一度に複数のドキュメントを MongoDB に挿入するために使用できます。どちらの方法を使用するかは、ニーズと個人的な好みによって異なります。