mongodb

MongoDB:批量插入(Bulk.insert)与多个插入(insert([...]))

小云
141
2023-09-26 02:42:45
栏目: 云计算

在MongoDB中,有两种方法可以用来插入多个文档:批量插入和多个插入。

批量插入使用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中。具体使用哪种方法取决于您的需求和个人偏好。

0
看了该问题的人还看了