我有一个项目我正在努力,我必须种植一个拥有1000万随机行的数据库,我已经成功完成了。然而,它需要大约30分钟才能完成,这是预期的,但我知道它可能会更快。我想让它运行得更快,并找到一种方法,使其在10分钟内播种1000万随机条目,最好还是使用mongodb / mongoose。这是我当前的种子文件,有关使其运行得更快的任何提示吗?第一次在这里张贴,只是fyi。谢谢!
我使用'node database / seed.js'在终端中运行此文件。
const db = require("./index.js");
const mongoose = require("mongoose");
const faker = require("faker");
const productSchema = mongoose.Schema({
product_name: String,
image: String,
price: String
});
let Product = mongoose.model("Product", productSchema);
async function seed() {
for (let i = 0; i < 10000000; i++) {
let name = faker.commerce.productName();
let image = faker.image.imageUrl();
let price = faker.commerce.price();
let item = new Product({
product_name: `${name}`,
image: `${image}`,
price: `$${price}`
});
await item
.save()
.then(success => {})
.catch(err => {});
}
}
seed();
您可以创建可能是100万条记录的批次,并可以使用insertMany函数将批量插入数据库。
插入/更新总是需要时间在所有类型的数据库中。尽量减少插入次数。
每1000次插入一次或循环一次
Model.insertMany(arr, function(error, docs) {});