微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐