Skip to content

Go Mongodb Bulk Write

DodaTech 1 min read

In this tutorial, you'll learn about MongoDB Bulk Write: Ordered vs Unordered. We cover key concepts, practical examples, and best practices.

MongoDB bulk write -- Use bulk write operations for efficient batch inserts, updates, and deletes.

The Problem

Ordered bulk writes stop on first error. Unordered bulk writes continue even if some operations fail. Choose based on whether operations are independent.

Wrong

models := []mongo.WriteModel{
    mongo.NewInsertOneModel().SetDocument(bson.M{"_id": 1}),
    mongo.NewInsertOneModel().SetDocument(bson.M{"_id": 1}), // Duplicate!
    mongo.NewInsertOneModel().SetDocument(bson.M{"_id": 2}),
}
results, err := collection.BulkWrite(ctx, models) // Fails on duplicate

Output:

// Second insert fails, third never attempted (ordered)
results, err := collection.BulkWrite(ctx, models,
    options.BulkWrite().SetOrdered(false))
// Even with duplicate error, document 2 is inserted

Output:

// Inserted: 2 documents (ID 1 once, ID 2 once).
// 1 error for duplicate

Prevention

  • Ordered stops on first error (default)
  • Unordered continues on error
  • Use InsertOneModel, UpdateOneModel, DeleteOneModel
  • Check results.InsertedCount, results.ModifiedCount
  • Use unordered for independent operations

Common Mistakes with mongodb bulk write

  1. Using foldl instead of foldl' causing stack overflow on large lists
  2. Forgetting deriving (Show, Eq) on custom data types needed for debugging
  3. Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable

These mistakes appear frequently in real-world GO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

**How to do bulk update?**

mongo.NewUpdateOneModel().SetFilter(bson.M{"status": "old"}).SetUpdate(bson.M{"$set": bson.M{"status": "new"}}).

What is max batch size?

100,000 operations or 48MB.

Can I mix operations?

Yes. Mix Insert, Update, Delete in one BulkWrite call.


Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tutorials help Go developers build production-ready software used by millions.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro