MongoDB Method: db.collection.insertMany()

Summary

Method Namedb.collection.insertMany()
UsageInsert multiple documents
Group write

Signature

db.collection.insertMany([document, document, document, ...], { writeConcern, ordered })

Usage

Insert multiple documents to collection. We provide an array of documents, and each of those documents are added to the collection.

NOTES

  • If the collection does not already exist, then a collection will be created first when we apply this insertMany() method.

Arguments

ParameterDescriptionTypeOptionalDefault
documentThe documents array that we want to insert into a collectiondocument
writeConcernA document with write concern, which indicates the level of acknowledgmentdocumentyes
orderedWheather to perform an ordered insertbooleanyestrue

NOTES

  • While inserting multiple documents, if any of the documents fail to be inserted and throw an error, then the execution process may or may not stop at that point. the “ordered” argument has an effect on this-
    • If ordered=true: operation stops and will not continue if any error happens in any document insertion.
    • if ordered=false: the operation will continue inserting documents.

Return Value

Return valueCase for the return valueType
A documentOn success this method returns a documentdocument
errorIf we try to insert document with an existing _iderror

NOTES

  • If _id field is not provided in the provided for any document to insert, then a new _id will be created, using the ObjectId() method.
  • A success response looks like-
    {
    acknowledged: true,
    insertedIds: {
    '0': ObjectId("65cf63854e726e44220f9375"),
    '1': ObjectId("65cf63854e726e44220f9376"),
    '2': ObjectId("65cf63854e726e44220f9377")
    }
    }
  • If we try to insert a document that has an already existing _id, we get an error like below-
    MongoBulkWriteError: E11000 duplicate key error collection: bigboxcode.customer index: id dup key: { _id: 102 }

Examples

Here are a few examples of the method usage-

# MongoDB db.collection.insertMany() method demo

# Insert some documents
bigboxcode> db.customer.insertMany([
    {
    "name": "Izabella Conroy",
    "age": 19,
    "phone": "108-679-2154",
    "address": {
      "street": "11 North Vineyard Drive",
      "city": "Pueblo West",
      "state": "CO",
      "postalCode": "81007"
    }
  },
  {
    "name": "Alisa Parker",
    "age": 72,
    "phone": "768-319-1054",
    "address": {
      "street": "8532 Ingalls Circle",
      "city": "Arvada",
      "state": "CO",
      "postalCode": "80003"
    }
  },
  {
    "name": "Eloise Weber",
    "age": 29,
    "phone": "618-357-2104",
    "address": {
      "street": "632 Belmar Drive",
      "city": "Edmond",
      "state": "OK",
      "postalCode": "73025"
    }
  }
])


output>
{
  acknowledged: true,
  insertedIds: {
    '0': ObjectId("65cf63854e726e44220f9375"),
    '1': ObjectId("65cf63854e726e44220f9376"),
    '2': ObjectId("65cf63854e726e44220f9377")
  }
}


# Insert documents with _id, the provided ids will be used
bigboxcode> db.customer.insertMany([
  {
    _id: 101,
    "name": "Laurianne Feil",
    "age": 34,
    "phone": "(519) 971-2871",
    "address": {
      "street": "1885 Moro Dr",
      "city": "Windsor",
      "state": "Ontario",
      "postalCode": "N9A 6J3",
      "country": "Canada"
    }
  },
  {
    _id: 102,
    "name": "Eleanore Padberg",
    "age": 35,
    "phone": "(709) 834-4002",
    "address": {
      "street": "834 Conception Bay Hwy",
      "city": "Conception Bay South",
      "state": "Newfoundland and Labrador",
      "postalCode": "A1X 7T4",
      "country": "Canada"
    }
  }
])


output>
{ 
  acknowledged: true, 
  insertedIds: { 
    '0': 101, 
    '1': 102 
  } 
}

# Use exixsing _id while inserting a document
# The insertion will fail, and the method returns an error
bigboxcode> db.customer.insertMany([
  {
    "name": "Sage Batz",
    "age": 20
  },
  {
    _id: 102,
    "name": "Maureen Koepp",
    "age": 55
  }
])


output>
Uncaught:
MongoBulkWriteError: E11000 duplicate key error collection: bigboxcode.customer index: _id_ dup key: { _id: 102 }
Result: BulkWriteResult {
  insertedCount: 1,
  matchedCount: 0,
  modifiedCount: 0,
  deletedCount: 0,
  upsertedCount: 0,
  upsertedIds: {},
  insertedIds: { '0': ObjectId('65cf662f82913eadf267bbbe') }
}
Write Errors: [
  WriteError {
    err: {
      index: 1,
      code: 11000,
      errmsg: 'E11000 duplicate key error collection: bigboxcode.customer index: _id_ dup key: { _id: 102 }',
      errInfo: undefined,
      op: { _id: 102, name: 'Maureen Koepp', age: 55 }
    }
  }
]


# If we use an existing _id, then the document insertion fails
# Also the documents after that are not inserted
bigboxcode> db.customer.insertMany([
  {
    "name": "Lauretta Schultz",
    "age": 20
  },
  {
    _id: 102,
    "name": "Samantha Crona",
    "age": 55
  },
  {
    _id: 110,
    "name": "Theo White",
    "age": 55
  }
])


output>
Uncaught:
MongoBulkWriteError: E11000 duplicate key error collection: bigboxcode.customer index: _id_ dup key: { _id: 102 }
Result: BulkWriteResult {
  insertedCount: 1,
  matchedCount: 0,
  modifiedCount: 0,
  deletedCount: 0,
  upsertedCount: 0,
  upsertedIds: {},
  insertedIds: { '0': ObjectId('65cf66f682913eadf267bbbf') }
}
Write Errors: [
  WriteError {
    err: {
      index: 1,
      code: 11000,
      errmsg: 'E11000 duplicate key error collection: bigboxcode.customer index: _id_ dup key: { _id: 102 }',
      errInfo: undefined,
      op: { _id: 102, name: 'Samantha Crona', age: 55 }
    }
  }
]

# Use existing _id, with ordered=false
# The docuemnt with existing id failed
# But other documents are inserted
bigboxcode> db.customer.insertMany([
  {
    "name": "Mavis Schmitt",
    "age": 20
  },
  {
    _id: 102,
    "name": "Reva Gutkowski",
    "age": 55
  },
  {
    _id: 110,
    "name": "Braulio Schmidt",
    "age": 55
  },
  {
    "name": "Ressie Lynch",
    "age": 22
  }
], { ordered: false })

output>
Uncaught:
MongoBulkWriteError: E11000 duplicate key error collection: bigboxcode.customer index: _id_ dup key: { _id: 102 }
Result: BulkWriteResult {
  insertedCount: 3,
  matchedCount: 0,
  modifiedCount: 0,
  deletedCount: 0,
  upsertedCount: 0,
  upsertedIds: {},
  insertedIds: {
    '0': ObjectId('65cf6d7d82913eadf267bbc0'),
    '2': 110,
    '3': ObjectId('65cf6d7d82913eadf267bbc1')
  }
}
Write Errors: [
  WriteError {
    err: {
      index: 1,
      code: 11000,
      errmsg: 'E11000 duplicate key error collection: bigboxcode.customer index: _id_ dup key: { _id: 102 }',
      errInfo: undefined,
      op: { _id: 102, name: 'Reva Gutkowski', age: 55 }
    }
  }
]

NOTES

  • if ordered=false, then the operation continues even after error happens. and the later documents are inserted.

Code Implementations

Here are the usage examples of the MongoDB method in Golang, NodeJS, Java, Python programming languages.

// MongoDB db.collection.insertMany() method examples in Golang

package main

import (
	"context"
	"fmt"
	"os"
	"time"

	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

const uri = "mongodb://bigboxuser:bigboxpass@localhost:27017/?maxPoolSize=20&w=majority"

type Customer struct {
	ID      int     `bson:"_id,omitempty"`
	Name    string  `bson:"name"`
	Age     int     `bson:"age"`
	Phone   string  `bson:"phone,omitempty"`
	Address Address `bson:"address,omitempty"`
}

type Address struct {
	Street     string `bson:"street,omitempty"`
	City       string `bson:"city,omitempty"`
	State      string `bson:"state,omitempty"`
	PostalCode string `bson:"postalCode,omitempty"`
	Country    string `bson:"country,omitempty"`
}

func main() {
	// Initiate mongo client
	mongoClient, err := mongo.Connect(context.TODO(), options.Client().ApplyURI(uri))
	if err != nil {
		fmt.Println("MongoDB connection error: ", err)
		os.Exit(1)
	}
	defer mongoClient.Disconnect(context.Background())

	// Initiate collection instance
	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()

	customerCollection := mongoClient.Database("bigboxcode").Collection("customer")

	// Insert some documents
	customers := []interface{}{
		Customer{
			Name:  "Izabella Conroy",
			Age:   19,
			Phone: "108-679-2154",
			Address: Address{
				Street:     "11 North Vineyard Drive",
				City:       "Pueblo West",
				State:      "CO",
				PostalCode: "81007",
			},
		},
		Customer{
			Name:  "Alisa Parker",
			Age:   72,
			Phone: "768-319-1054",
			Address: Address{
				Street:     "8532 Ingalls Circle",
				City:       "Arvada",
				State:      "CO",
				PostalCode: "80003",
			},
		},
		Customer{
			Name:  "Eloise Weber",
			Age:   29,
			Phone: "618-357-2104",
			Address: Address{
				Street:     "632 Belmar Drive",
				City:       "Edmond",
				State:      "OK",
				PostalCode: "73025",
			},
		},
	}

	commandResult, err := customerCollection.InsertMany(ctx, customers)

	if err != nil {
		fmt.Println("Command: db.customer.insertMany(... 3 documents ) | ERROR: ", err)
	}

	fmt.Println("Command: db.customer.insertMany(... 3 documents ) | Result: ", commandResult)

	// Insert documents with _id, the provided ids will be used
	customers = []interface{}{
		Customer{
			ID:    101,
			Name:  "Laurianne Feil",
			Age:   34,
			Phone: "(519) 971-2871",
			Address: Address{
				Street:     "1885 Moro Dr",
				City:       "Windsor",
				State:      "Ontario",
				PostalCode: "N9A 6J3",
				Country:    "Canada",
			},
		},
		Customer{
			ID:    102,
			Name:  "Eleanore Padberg",
			Age:   35,
			Phone: "(709) 834-4002",
			Address: Address{
				Street:     "834 Conception Bay Hwy",
				City:       "Conception Bay South",
				State:      "Newfoundland and Labrador",
				PostalCode: "A1X 7T4",
				Country:    "Canada",
			},
		},
	}
	commandResult, err = customerCollection.InsertMany(ctx, customers)

	if err != nil {
		fmt.Println("Command: db.customer.insertMany(... 2 documents with _id) | ERROR: ", err)
	}

	fmt.Println("Command: db.customer.insertMany(... 2 documents with _id) | Result: ", commandResult)

	// Use exixsing _id while inserting a document
	// The insertion will fail, and the method returns an error
	customers = []interface{}{
		Customer{
			Name: "Sage Batz",
			Age:  20,
		},
		Customer{
			ID:   102,
			Name: "Maureen Koepp",
			Age:  55,
		},
	}
	commandResult, err = customerCollection.InsertMany(ctx, customers)

	if err != nil {
		fmt.Println("Command: db.customer.insertMany(... one with existing _id) | ERROR: ", err)
	}

	fmt.Println("Command: db.customer.insertMany(... one with existing _id) | Result: ", commandResult)

	// If we use an existing _id, then the document insertion fails
	// Also the documents after that are not inserted
	commandResult, err = customerCollection.InsertMany(ctx, []interface{}{
		Customer{
			Name: "Lauretta Schultz",
			Age:  20,
		},
		Customer{
			ID:   102,
			Name: "Samantha Crona",
			Age:  55,
		},
		Customer{
			ID:   110,
			Name: "Theo White",
			Age:  55,
		},
	})

	if err != nil {
		fmt.Println("Command: db.customer.insertMany(... one with existing id) | ERROR: ", err)
	}

	fmt.Println("Command: db.customer.insertMany(... one with existing id) | Result: ", commandResult)

	// Use existing _id, with ordered=false
	// The docuemnt with existing id failed
	// But other documents are inserted
	opts := options.InsertMany().SetOrdered(false)
	commandResult, err = customerCollection.InsertMany(ctx, []interface{}{
		Customer{
			Name: "Mavis Schmitt",
			Age:  20,
		},
		Customer{
			ID:   102,
			Name: "Reva Gutkowski",
			Age:  55,
		},
		Customer{
			ID:   110,
			Name: "Braulio Schmidt",
			Age:  55,
		},
		Customer{
			Name: "Ressie Lynch",
			Age:  22,
		},
	}, opts)

	if err != nil {
		fmt.Println("Command: db.customer.insertMany(... 4 documents 1 has existing id, {ordered: false}) | ERROR: ", err)
	}

	fmt.Println("Command: db.customer.insertMany(... 4 documents 1 has existing id, {ordered: false}) | Result: ", commandResult)

}

Output:

Command: db.customer.insertMany(... 3 documents ) | Result:  &{[ObjectID("65d06d712c227b2d336031e1") ObjectID("65d06d712c227b2d336031e2") ObjectID("65d06d712c227b2d336031e3")]}

Command: db.customer.insertMany(... 2 documents with _id) | Result:  &{[101 102]}

Command: db.customer.insertMany(... one with existing _id) | ERROR:  bulk write exception: write errors: [E11000 duplicate key error collection: bigboxcode.customer index: _id_ dup key: { _id: 102 }]
Command: db.customer.insertMany(... one with existing _id) | Result:  &{[ObjectID("65d06d712c227b2d336031e6")]}

Command: db.customer.insertMany(... one with existing id) | ERROR:  bulk write exception: write errors: [E11000 duplicate key error collection: bigboxcode.customer index: _id_ dup key: { _id: 102 }]
Command: db.customer.insertMany(... one with existing id) | Result:  &{[ObjectID("65d06d712c227b2d336031e8")]}

Command: db.customer.insertMany(... 4 documents 1 has existing id, {ordered: false}) | ERROR:  bulk write exception: write errors: [E11000 duplicate key error collection: bigboxcode.customer index: _id_ dup key: { _id: 102 }]
Command: db.customer.insertMany(... 4 documents 1 has existing id, {ordered: false}) | Result:  &{[ObjectID("65d06d712c227b2d336031eb") 110 ObjectID("65d06d712c227b2d336031ee")]}

NOTES

  • Use the “InsertMany()” method from “mongo-go-driver
  • Signature of the method-
    • func (coll *Collection) InsertMany(ctx context.Context, documents []interface{}, opts ...*options.InsertManyOptions) (*InsertManyResult, error)
  • Definition of InsertManyOptions

    type InsertManyOptions struct {
        BypassDocumentValidation *bool
        Comment interface{}
        Ordered *bool
    }
// db.collection.insertMany() method example in NodeJS

import { MongoClient } from "mongodb";

// Define MongoDB connection URI
const uri = "mongodb://bigboxuser:bigboxpass@127.0.0.1:27017";

// Create a client
const mongo = new MongoClient(uri);

await mongo.connect();

const database = mongo.db("bigboxcode");
const customerCollection = database.collection("customer");

// Insert some documents
let commandResult = await customerCollection.insertMany([
  {
    name: "Izabella Conroy",
    age: 19,
    phone: "108-679-2154",
    address: {
      street: "11 North Vineyard Drive",
      city: "Pueblo West",
      state: "CO",
      postalCode: "81007",
    },
  },
  {
    name: "Alisa Parker",
    age: 72,
    phone: "768-319-1054",
    address: {
      street: "8532 Ingalls Circle",
      city: "Arvada",
      state: "CO",
      postalCode: "80003",
    },
  },
  {
    name: "Eloise Weber",
    age: 29,
    phone: "618-357-2104",
    address: {
      street: "632 Belmar Drive",
      city: "Edmond",
      state: "OK",
      postalCode: "73025",
    },
  },
]);

console.log(
  "Command: db.customer.insertMany(... 3 documents ) | Result: ",
  commandResult
);

// Insert documents with _id, the provided ids will be used
commandResult = await customerCollection.insertMany([
  {
    _id: 101,
    name: "Laurianne Feil",
    age: 34,
    phone: "(519) 971-2871",
    address: {
      street: "1885 Moro Dr",
      city: "Windsor",
      state: "Ontario",
      postalCode: "N9A 6J3",
      country: "Canada",
    },
  },
  {
    _id: 102,
    name: "Eleanore Padberg",
    age: 35,
    phone: "(709) 834-4002",
    address: {
      street: "834 Conception Bay Hwy",
      city: "Conception Bay South",
      state: "Newfoundland and Labrador",
      postalCode: "A1X 7T4",
      country: "Canada",
    },
  },
]);

console.log(
  "Command: db.customer.insertMany(... 2 documents with _id) | Result: ",
  commandResult
);

// Use exixsing _id while inserting a document
// The insertion will fail, and the method returns an error
try {
  commandResult = await customerCollection.insertMany([
    {
      name: "Sage Batz",
      age: 20,
    },
    {
      _id: 102,
      name: "Maureen Koepp",
      age: 55,
    },
  ]);

  console.log(
    "Command: db.customer.insertMany(... one with existing _id) | Result: ",
    commandResult
  );
} catch (err) {
  console.log(
    "Command: db.customer.insertMany(... one with existing _id) | Error: ",
    err
  );
}

// If we use an existing _id, then the document insertion fails
// Also the documents after that are not inserted
try {
  commandResult = await customerCollection.insertMany([
    {
      name: "Lauretta Schultz",
      age: 20,
    },
    {
      _id: 102,
      name: "Samantha Crona",
      age: 55,
    },
    {
      _id: 110,
      name: "Theo White",
      age: 55,
    },
  ]);

  console.log(
    "Command: db.customer.insertMany(... one with existing id) | Result: ",
    commandResult
  );
} catch (err) {
  console.log(
    "Command: db.customer.insertMany(... one with existing id) | Error: ",
    err
  );
}

try {
  // Use existing _id, with ordered=false
  // The docuemnt with existing id failed
  // But other documents are inserted
  commandResult = await customerCollection.insertMany(
    [
      {
        name: "Mavis Schmitt",
        age: 20,
      },
      {
        _id: 102,
        name: "Reva Gutkowski",
        age: 55,
      },
      {
        _id: 110,
        name: "Braulio Schmidt",
        age: 55,
      },
      {
        name: "Ressie Lynch",
        age: 22,
      },
    ],
    { ordered: false }
  );

  console.log(
    "Command: db.customer.insertMany(... 4 documents 1 has existing id, {ordered: false}) | Result: ",
    commandResult
  );
} catch (err) {
  console.log(
    "Command: db.customer.insertMany(... 4 documents 1 has existing id, {ordered: false}) | Error: ",
    err
  );
}

// Close connection
await mongo.close();

process.exit(0);

Output:

Command: db.customer.insertMany(... 3 documents ) | Result:  {
  acknowledged: true,
  insertedCount: 3,
  insertedIds: {
    '0': new ObjectId('65cf7221c206b84c6129a81d'),
    '1': new ObjectId('65cf7221c206b84c6129a81e'),
    '2': new ObjectId('65cf7221c206b84c6129a81f')
  }
}


Command: db.customer.insertMany(... 2 documents with _id) | Result:  {
  acknowledged: true,
  insertedCount: 2,
  insertedIds: { '0': 101, '1': 102 }
}


Command: db.customer.insertMany(... one with existing _id) | Error:  
MongoBulkWriteError: E11000 duplicate key error collection: bigboxcode.customer index: _id_ dup key: { _id: 102 }
    at OrderedBulkOperation.handleWriteError (node_modulesmongodblibbulkcommon.js:823:22)
    at resultHandler (node_modulesmongodblibbulkcommon.js:302:27)
    at node_modulesmongodblibutils.js:274:28
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
  code: 11000,
  writeErrors: [ WriteError { err: [Object] } ],
  result: BulkWriteResult {
    insertedCount: 1,
    matchedCount: 0,
    modifiedCount: 0,
    deletedCount: 0,
    upsertedCount: 0,
    upsertedIds: {},
    insertedIds: { '0': new ObjectId('65cf7221c206b84c6129a820') }
  },
  [Symbol(errorLabels)]: Set(0) {}
}


Command: db.customer.insertMany(... one with existing id) | 
Error:  MongoBulkWriteError: E11000 duplicate key error collection: bigboxcode.customer index: _id_ dup key: { _id: 102 }
    at OrderedBulkOperation.handleWriteError (node_modulesmongodblibbulkcommon.js:823:22)
    at resultHandler (node_modulesmongodblibbulkcommon.js:302:27)
    at node_modulesmongodblibutils.js:274:28
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
  code: 11000,
  writeErrors: [ WriteError { err: [Object] } ],
  result: BulkWriteResult {
    insertedCount: 1,
    matchedCount: 0,
    modifiedCount: 0,
    deletedCount: 0,
    upsertedCount: 0,
    upsertedIds: {},
    insertedIds: { '0': new ObjectId('65cf7221c206b84c6129a821') }
  },
  [Symbol(errorLabels)]: Set(0) {}
}


Command: db.customer.insertMany(... 4 documents 1 has existing id, {ordered: false}) | Error:  
MongoBulkWriteError: E11000 duplicate key error collection: bigboxcode.customer index: _id_ dup key: { _id: 102 }
    at UnorderedBulkOperation.handleWriteError (node_modulesmongodblibbulkcommon.js:823:22)
    at UnorderedBulkOperation.handleWriteError (node_modulesmongodblibbulkunordered.js:17:22)
    at resultHandler (node_modulesmongodblibbulkcommon.js:302:27)
    at node_modulesmongodblibutils.js:274:28
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
  code: 11000,
  writeErrors: [ WriteError { err: [Object] } ],
  result: BulkWriteResult {
    insertedCount: 3,
    matchedCount: 0,
    modifiedCount: 0,
    deletedCount: 0,
    upsertedCount: 0,
    upsertedIds: {},
    insertedIds: {
      '0': new ObjectId('65cf7221c206b84c6129a822'),
      '2': 110,
      '3': new ObjectId('65cf7221c206b84c6129a823')
    }
  },
  [Symbol(errorLabels)]: Set(0) {}
}

NOTES

  • Use NodeJS “insertMany()” method from the package “mongodb“.
  • Method signatures are-
    • insertMany(docs: OptionalUnlessRequiredId<TSchema>[], options?: BulkWriteOptions): Promise<InsertManyResult<TSchema>>
  • Check the insertedCount in the result, in cases of failed operations. This indicates the number of successful document insertions.
# db.collection.insertMany() method example in Python

from pymongo import MongoClient, WriteConcern
import re
from datetime import datetime

# Create MongoDB client
mongo_client = MongoClient("mongodb://bigboxuser:bigboxpass@127.0.0.1:27017/")
# Select database and collection
mongo_database = mongo_client.bigboxcode
customer_collection = mongo_database.customer

# Insert some documents
command_result = customer_collection.insert_many(
    [
        {
            "name": "Izabella Conroy",
            "age": 19,
            "phone": "108-679-2154",
            "address": {
                "street": "11 North Vineyard Drive",
                "city": "Pueblo West",
                "state": "CO",
                "postalCode": "81007",
            },
        },
        {
            "name": "Alisa Parker",
            "age": 72,
            "phone": "768-319-1054",
            "address": {
                "street": "8532 Ingalls Circle",
                "city": "Arvada",
                "state": "CO",
                "postalCode": "80003",
            },
        },
        {
            "name": "Eloise Weber",
            "age": 29,
            "phone": "618-357-2104",
            "address": {
                "street": "632 Belmar Drive",
                "city": "Edmond",
                "state": "OK",
                "postalCode": "73025",
            },
        },
    ]
)

print(
    "Command: db.customer.insertMany(... 3 documents ) | Result: ",
    command_result.inserted_ids,
)

# Insert documents with _id, the provided ids will be used
command_result = customer_collection.insert_many(
    [
        {
            "_id": 101,
            "name": "Laurianne Feil",
            "age": 34,
            "phone": "(519) 971-2871",
            "address": {
                "street": "1885 Moro Dr",
                "city": "Windsor",
                "state": "Ontario",
                "postalCode": "N9A 6J3",
                "country": "Canada",
            },
        },
        {
            "_id": 102,
            "name": "Eleanore Padberg",
            "age": 35,
            "phone": "(709) 834-4002",
            "address": {
                "street": "834 Conception Bay Hwy",
                "city": "Conception Bay South",
                "state": "Newfoundland and Labrador",
                "postalCode": "A1X 7T4",
                "country": "Canada",
            },
        },
    ]
)

print(
    "Command: db.customer.insertMany(... 2 documents with _id) | Result: ",
    command_result.inserted_ids,
)

# Use existing _id while inserting a document
# The insertion will fail, and the method returns an error
try:
    command_result = customer_collection.insert_many(
        [
            {
                "name": "Sage Batz",
                "age": 20,
            },
            {
                "_id": 102,
                "name": "Maureen Koepp",
                "age": 55,
            },
        ]
    )
    print(
        "Command: db.customer.insertMany(... one with existing _id) | Result: ",
        command_result.inserted_ids,
    )
except Exception as err:
    print("Command: db.customer.insertMany(... one with existing _id) | Error: ", err)

# If we use an existing _id, then the document insertion fails
# Also the documents after that are not inserted
try:
    command_result = customer_collection.insert_many(
        [
            {
                "name": "Lauretta Schultz",
                "age": 20,
            },
            {
                "_id": 102,
                "name": "Samantha Crona",
                "age": 55,
            },
            {
                "_id": 110,
                "name": "Theo White",
                "age": 55,
            },
        ]
    )
    print(
        "Command: db.customer.insertMany(... one with existing id) | Result: ",
        command_result.inserted_ids,
    )
except Exception as err:
    print("Command: db.customer.insertMany(... one with existing id) | Error: ", err)

# Use existing _id, with ordered=False
# The document with existing id failed
# But other documents are inserted
try:
    command_result = customer_collection.insert_many(
        [
            {
                "name": "Mavis Schmitt",
                "age": 20,
            },
            {
                "_id": 102,
                "name": "Reva Gutkowski",
                "age": 55,
            },
            {
                "_id": 110,
                "name": "Braulio Schmidt",
                "age": 55,
            },
            {
                "name": "Ressie Lynch",
                "age": 22,
            },
        ],
        ordered=False,
    )
    print(
        "Command: db.customer.insertMany(... 4 documents 1 has existing id, {ordered: false}) | Result: ",
        command_result.inserted_ids,
    )
except Exception as err:
    print(
        "Command: db.customer.insertMany(... 4 documents 1 has existing id, {ordered: false}) | Error: ",
        err,
    )

# Close connection
mongo_client.close()

Output:

Command: db.customer.insertMany(... 3 documents ) | Result:  [ObjectId('65d0715b2d3d3cb0f07db9fe'), ObjectId('65d0715b2d3d3cb0f07db9ff'), ObjectId('65d0715b2d3d3cb0f07dba00')]

Command: db.customer.insertMany(... 2 documents with _id) | Result:  [101, 102]

Command: db.customer.insertMany(... one with existing _id) | Error:  batch op errors occurred, full error: {'writeErrors': [{'index': 1, 'code': 11000, 'errmsg': 'E11000 duplicate key error collection: bigboxcode.customer index: _id_ dup key: { _id: 102 }', 'keyPattern': {'_id': 1}, 'keyValue': {'_id': 102}, 'op': {'_id': 102, 'name': 'Maureen Koepp', 'age': 55}}], 'writeConcernErrors': [], 'nInserted': 1, 'nUpserted': 0, 'nMatched': 0, 'nModified': 0, 'nRemoved': 0, 'upserted': []}

Command: db.customer.insertMany(... one with existing id) | Error:  batch op errors occurred, full error: {'writeErrors': [{'index': 1, 'code': 11000, 'errmsg': 'E11000 duplicate key error collection: bigboxcode.customer index: _id_ dup key: { _id: 102 }', 'keyPattern': {'_id': 1}, 'keyValue': {'_id': 102}, 'op': {'_id': 102, 'name': 'Samantha Crona', 'age': 55}}], 'writeConcernErrors': [], 'nInserted': 1, 'nUpserted': 0, 'nMatched': 0, 'nModified': 0, 'nRemoved': 0, 'upserted': []}

Command: db.customer.insertMany(... 4 documents 1 has existing id, {ordered: false}) | Error:  batch op errors occurred, full error: {'writeErrors': [{'index': 1, 'code': 11000, 'errmsg': 'E11000 duplicate key error collection: bigboxcode.customer index: _id_ dup key: { _id: 102 }', 'keyPattern': {'_id': 1}, 'keyValue': {'_id': 102}, 'op': {'_id': 102, 'name': 'Reva Gutkowski', 'age': 55}}], 'writeConcernErrors': [], 'nInserted': 3, 'nUpserted': 0, 'nMatched': 0, 'nModified': 0, 'nRemoved': 0, 'upserted': []}

NOTES

  • Use method “insert_many” from redis-py.
  • Signature of the method is –
    • def insert_many(
              self,
              documents: Iterable[Union[_DocumentType, RawBSONDocument]],
              ordered: bool = True,
              bypass_document_validation: bool = False,
              session: Optional[ClientSession] = None,
              comment: Optional[Any] = None,
      ) -> InsertManyResult
// db.collection.insertMany() method example in Java

import com.mongodb.client.*;
import com.mongodb.client.model.InsertManyOptions;
import com.mongodb.client.result.InsertManyResult;
import org.bson.Document;

import java.util.ArrayList;
import java.util.List;

public class InsertMany {
    public static void main(String[] args) {
        String uri = "mongodb://bigboxuser:bigboxpass@localhost:27017/";

        try (MongoClient mongoClient = MongoClients.create(uri)) {
            MongoDatabase database = mongoClient.getDatabase("bigboxcode");
            MongoCollection<Document> customerCollection = database.getCollection("customer");

            // Insert some documents
            List<Document> documents = new ArrayList<>();
            documents.add(new Document("name", "Izabella Conroy")
                    .append("age", 19)
                    .append("phone", "108-679-2154")
                    .append("address", new Document("street", "11 North Vineyard Drive")
                            .append("city", "Pueblo West")
                            .append("state", "CO")
                            .append("postalCode", "81007")));
            documents.add(new Document("name", "Alisa Parker")
                    .append("age", 72)
                    .append("phone", "768-319-1054")
                    .append("address", new Document("street", "8532 Ingalls Circle")
                            .append("city", "Arvada")
                            .append("state", "CO")
                            .append("postalCode", "80003")));
            documents.add(new Document("name", "Eloise Weber")
                    .append("age", 29)
                    .append("phone", "618-357-2104")
                    .append("address", new Document("street", "632 Belmar Drive")
                            .append("city", "Edmond")
                            .append("state", "OK")
                            .append("postalCode", "73025")));

            InsertManyResult result = customerCollection.insertMany(documents);
            System.out.println("Command: db.customer.insertMany(... 3 documents ) | Result: " + result);

            // Insert documents with _id, the provided ids will be used
            documents.clear();
            documents.add(new Document("_id", 101)
                    .append("name", "Laurianne Feil")
                    .append("age", 34)
                    .append("phone", "(519) 971-2871")
                    .append("address", new Document("street", "1885 Moro Dr")
                            .append("city", "Windsor")
                            .append("state", "Ontario")
                            .append("postalCode", "N9A 6J3")
                            .append("country", "Canada")));
            documents.add(new Document("_id", 102)
                    .append("name", "Eleanore Padberg")
                    .append("age", 35)
                    .append("phone", "(709) 834-4002")
                    .append("address", new Document("street", "834 Conception Bay Hwy")
                            .append("city", "Conception Bay South")
                            .append("state", "Newfoundland and Labrador")
                            .append("postalCode", "A1X 7T4")
                            .append("country", "Canada")));

            result = customerCollection.insertMany(documents);
            System.out.println("Command: db.customer.insertMany(... 2 documents with _id) | Result: " + result);

            // Use existing _id while inserting a document
            // The insertion will fail, and the method returns an error
            documents.clear();
            documents.add(new Document("name", "Sage Batz").append("age", 20));
            documents.add(new Document("_id", 102).append("name", "Maureen Koepp").append("age", 55));

            try {
                result = customerCollection.insertMany(documents);
                System.out.println("Command: db.customer.insertMany(... one with existing _id) | Result: " + result);
            } catch (Exception e) {
                System.out.println("Command: db.customer.insertMany(... one with existing _id) | Error: " + e.getMessage());
            }

            // If we use an existing _id, then the document insertion fails
            // Also the documents after that are not inserted
            documents.clear();
            documents.add(new Document("name", "Lauretta Schultz").append("age", 20));
            documents.add(new Document("_id", 102).append("name", "Samantha Crona").append("age", 55));
            documents.add(new Document("_id", 110).append("name", "Theo White").append("age", 55));

            try {
                result = customerCollection.insertMany(documents);
                System.out.println("Command: db.customer.insertMany(... one with existing id) | Result: " + result);
            } catch (Exception e) {
                System.out.println("Command: db.customer.insertMany(... one with existing id) | Error: " + e.getMessage());
            }

            // Use existing _id, with ordered=false
            // The document with existing id failed
            // But other documents are inserted
            documents.clear();
            documents.add(new Document("name", "Mavis Schmitt").append("age", 20));
            documents.add(new Document("_id", 102).append("name", "Reva Gutkowski").append("age", 55));
            documents.add(new Document("_id", 110).append("name", "Braulio Schmidt").append("age", 55));
            documents.add(new Document("name", "Ressie Lynch").append("age", 22));

            InsertManyOptions options = new InsertManyOptions().ordered(false);
            try {
                result = customerCollection.insertMany(documents, options);
                System.out.println("Command: db.customer.insertMany(... 4 documents 1 has existing id, {ordered: false}) | Result: " + result);
            } catch (Exception e) {
                System.out.println("Command: db.customer.insertMany(... 4 documents 1 has existing id, {ordered: false}) | Error: " + e.getMessage());
            }

            // Close connection
            mongoClient.close();
        }

    }
}

Output:

Command: db.customer.insertMany(... 3 documents ) | Result: AcknowledgedInsertManyResult{insertedIds={0=BsonObjectId{value=65d07359e46bcf5db193a178}, 1=BsonObjectId{value=65d07359e46bcf5db193a179}, 2=BsonObjectId{value=65d07359e46bcf5db193a17a}}}

Command: db.customer.insertMany(... 2 documents with _id) | Result: AcknowledgedInsertManyResult{insertedIds={0=BsonInt32{value=101}, 1=BsonInt32{value=102}}}

Command: db.customer.insertMany(... one with existing _id) | Error: Bulk write operation error on server localhost:27017. Write errors: [BulkWriteError{index=1, code=11000, message='E11000 duplicate key error collection: bigboxcode.customer index: _id_ dup key: { _id: 102 }', details={}}]. 

Command: db.customer.insertMany(... one with existing id) | Error: Bulk write operation error on server localhost:27017. Write errors: [BulkWriteError{index=1, code=11000, message='E11000 duplicate key error collection: bigboxcode.customer index: _id_ dup key: { _id: 102 }', details={}}]. 

Command: db.customer.insertMany(... 4 documents 1 has existing id, {ordered: false}) | Error: Bulk write operation error on server localhost:27017. Write errors: [BulkWriteError{index=1, code=11000, message='E11000 duplicate key error collection: bigboxcode.customer index: _id_ dup key: { _id: 102 }', details={}}]. 

NOTES

  • Use the method “iinsertMany()” from MongoCollection.
  • Signatures of the method are-
    • InsertManyResult insertMany(List<? extends TDocument> documents);
    • InsertManyResult insertMany(List<? extends TDocument> documents, InsertManyOptions options);
    • InsertManyResult insertMany(ClientSession clientSession, List<? extends TDocument> documents);
    • InsertManyResult insertMany(ClientSession clientSession, List<? extends TDocument> documents, InsertManyOptions options);

Source Code

Use the following links to get the source code used in this article-

Related Methods

CommandDetails
db.collection.insertOne() Method Details
db.collection.bulkWrite() Method Details

Leave a Comment


The reCAPTCHA verification period has expired. Please reload the page.