0

I have a collection of 12K models and I want to insert in my Mongo DB.

Mongo db version: 4.0.3 Mongoose version: 5.3.4

I tried with InsertMany, create, save() into forEach but I can't insert my 12K models.

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) => {

});

Only when the length of the array is less than 1K works ok. I read about since Mongo 3.6 the maxWriteBatchSize is 100K. I'm using Mongo 4. I don't understand why not works with only 12K elements.

The console doesn't show errors.

Jonathan Brizio
  • 1,087
  • 1
  • 14
  • 28
Gere
  • 2,114
  • 24
  • 24

1 Answers1

1

Finally I resolved using mongo driver for javascript and a batch size logic:

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();
Gere
  • 2,114
  • 24
  • 24