如何将多个项目项同时插入MongoDB集合?

问题描述 投票:0回答:1

我有一个12K模型的集合,我想插入我的Mongo数据库。

Mongodb版本:4.0.3 Mongoose版本:5.3.4

我尝试使用InsertMany,创建,save()到forEach但我无法插入我的12K模型。

const ProductSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true
  },
  id: {
    type: String,
    required: true
  },
  sku: {
    type: String,
    required: true
  },
  categoriesIds: [
    {
      type: String
    }
  ]},
  {
    usePushEach: true, timestamps: true
  });

 const prodModel = new ProductModel({
              name: prod.name,
              id: prod.id,
              sku: prod.sku,
              categoriesIds: prod.categories
            });

I have array of 12K productModel created and then I did:


ProductModel.insertMany(products, (error) => {

});

只有当数组的长度小于1K才能正常工作。我读到自Mongo 3.6以来maxWriteBatchSize是100K。我正在使用Mongo 4.我不明白为什么不能只使用12K元素。

控制台不显示错误。

node.js mongodb mongoose
1个回答
1
投票

最后我解决了使用mongo驱动程序的javascript和批量大小逻辑:

const batchSize = 1000;
        const col = db.collection('products');
        let batch = col.initializeUnorderedBulkOp();
        for (let i = 0; i <= products.length; i += 1) {
          if (products[i]) {
            batch.insert(products[i]);
            if (i % batchSize === 0) {
              batch.execute();
              batch = col.initializeUnorderedBulkOp();
            }
          }
        }
        return batch.execute();
© www.soinside.com 2019 - 2024. All rights reserved.