MongoDB Method: db.collection.insertOne()

Summary

Method Namedb.collection.insertOne()
UsageInsert single document
Group write

Signature

db.collection.insertOne(document, writeConcern)

Usage

Insert one document to collection. This command is recommended if we just need to add only one document.

NOTES

  • If the collection does not already exist, then a collection will be created first when we apply this insertOne() method.
  • BSON document has a size limit of 16 MB. So, the max size of a single document that we can insert into MongoDB is 16 Megabytes.

Arguments

ParameterDescriptionTypeOptional
documentThe document that we want to insert into a collectiondocument
writeConcernA document with write concern, which indicates the level of acknowledgmentdocumentTrue

NOTES

  • Usually, the writeConcern param is ignored, in that case, the default writeConcern will be used.
  • writeConcern should be a document, that can have the following fields:
    w= number of acknowledgments from the number of nodes
    j= confirmation of data written on disk
    wtimeout= operation timeout limit in milliseconds

    For example, a writeConcern value would be like the below-
    {w: "majority", j: false}
    or like {w: 2, j: true, wtiemout: 10000}

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 document to insert, then a new _id will be created, using the the ObjectId() method.
  • A success response looks like this-
    {
    acknowledged: true,
    insertedId: ObjectId('65c4de9e2d7236b44a64547e')
    }
  • If we try to insert a document that has an already existing _id, we get an error like below-
    MongoServerError: E11000 duplicate key error collection: bigboxcode.customer index: id dup key: { _id: 99 }

Examples

Here are a few examples of the method usage-

# MongoDB db.collection.insertOne() method demo

# Insert one document
bigboxcode> db.customer.insertOne({
    name: "john doe", 
    age: 34
})

output:
{
  acknowledged: true,
  insertedId: ObjectId('65c4de9e2d7236b44a64547e')
}


# Insert document with _id defined
bigboxcode> db.customer.insertOne({
    _id: 99, 
    name: "Leatha Ledner", 
    age: 54
})

output:
{ 
    acknowledged: true, 
    insertedId: 99
}


# Try to add a document with an existing _id
# We get an error
bigboxcode> db.customer.insertOne({
    _id: 99, 
    name: "Sophia Gray", 
    age: 25
})

output:
MongoServerError: E11000 duplicate key error collection: bigboxcode.customer index: _id_ dup key: { _id: 99 }

# Provide writeConcern to insertOne
bigboxcode> db.customer.insertOne({
    _id: 100, 
    name: "Sophia Gray", 
    age: 25
}, {writeConcern: {w: "majority", wtimeout: 100}})

output:
{ 
    acknowledged: true, 
    insertedId: 100 
}

# Insert nested document
bigboxcode> db.customer.insertOne({
    name: "Devonte Greenholt", 
    dob: ISODate("1976-01-12T06:00:00Z"), 
    address: { 
        street: "1114 Edmonton Trail NE", 
        city: "Calgary", 
        state: "Alberta", 
        zip: "T2E 0Z2", 
        phone: "(403) 277-3408", 
        country: "canada"
    }
})

output:
{
  acknowledged: true,
  insertedId: ObjectId('65c709112d7236b44a64547f')
}

NOTES

  • We can provide _id, or leave it for MongoDB to generate it.

Code Implementations

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

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

package main

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

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

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

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 one document
	commandResult, err := customerCollection.InsertOne(ctx, map[string]interface{}{
		"name": "john doe",
		"age":  34,
	})

	fmt.Println("Command: db.customer.insertOne({name: "john doe", age: 34}) | Result: ", commandResult)

	// Insert document with _id defined
	commandResult, err = customerCollection.InsertOne(ctx, map[string]interface{}{
		"_id":  99,
		"name": "Leatha Ledner",
		"age":  54,
	})

	if err != nil {
		fmt.Println(err)
	}

	fmt.Println("Command: db.customer.insertOne({_id: 99, name: "Leatha Ledner", age: 54}) | Result: ", commandResult)

	// Try to add a document with an existing _id
	// We get an error
	commandResult, err = customerCollection.InsertOne(ctx, map[string]interface{}{
		"_id":  99,
		"name": "Sophia Gray",
		"age":  25,
	})

	if err != nil {
		fmt.Println(err)
	}

	fmt.Println("Command: db.customer.insertOne({_id: 99, name: "Sophia Gray", age: 25}) | Result: ", commandResult)

	// Provide writeConcern to insertOne
	commandResult, err = customerCollection.InsertOne(ctx, map[string]interface{}{
		"_id":  100,
		"name": "Sophia Gray",
		"age":  25,
	})

	if err != nil {
		fmt.Println(err)
	}

	fmt.Println("Command: db.customer.insertOne({_id: 100, name: "Sophia Gray", age: 25}, {writeConcern: {w: "majority", wtimeout: 100}}}) | Result: ", commandResult)

	// Insert nested document
	parsedTime, err := time.Parse(time.RFC3339, "1976-01-12T06:00:00Z")

	if err != nil {
		fmt.Println(err)
	}

	commandResult, err = customerCollection.InsertOne(ctx, bson.M{
		"name": "Devonte Greenholt",
		"dob":  parsedTime,
		"address": bson.M{
			"street":  "1114 Edmonton Trail NE",
			"city":    "Calgary",
			"state":   "Alberta",
			"zip":     "T2E 0Z2",
			"phone":   "(403) 277-3408",
			"country": "canada",
		},
	})

	if err != nil {
		fmt.Println(err)
	}

	fmt.Println("Command: db.customer.insertOne(name: "Devonte Greenholt", dob: ISODate("1976-01-12T06:00:00Z"), address: { street: "1114 Edmonton Trail NE", city: "Calgary", state: "Alberta", zip: "T2E 0Z2", phone: "(403) 277-3408", country: "canada"}) | Result: ", commandResult)

}

Output:

Command: db.customer.insertOne({name: "john doe", age: 34}) | Result:  &{ObjectID("65c8afd3bce0c3360f263271")}

Command: db.customer.insertOne({_id: 99, name: "Leatha Ledner", age: 54}) | Result:  &{99}

write exception: write errors: [E11000 duplicate key error collection: bigboxcode.customer index: _id_ dup key: { _id: 99 }]   
     
Command: db.customer.insertOne({_id: 99, name: "Sophia Gray", age: 25}) | Result:  <nil>

Command: db.customer.insertOne({_id: 100, name: "Sophia Gray", age: 25}, {writeConcern: {w: "majority", wtimeout: 100}}}) | Result:  &{100}

Command: db.customer.insertOne(name: "Devonte Greenholt", dob: ISODate("1976-01-12T06:00:00Z"), address: { street: "1114 Edmonton Trail NE", city: "Calgary", state: "Alberta", zip: "T2E 0Z2", phone: "(403) 277-3408", country: "canada"}) | Result:  &{ObjectID("65c8afd3bce0c3360f263275")}

NOTES

  • Use the “InsertOne()” method from “mongo-go-driver
  • Signature of the method-
    • func (coll *Collection) InsertOne(ctx context.Context, document interface{}, opts ...*options.InsertOneOptions) (*InsertOneResult, error)
  • Definition of FindOneOptions

    type FindOneOptions struct {
        AllowPartialResults *bool
        BatchSize *int32
        Collation *Collation
        Comment *string
        CursorType *CursorType
        Hint interface{}
        Max interface{}
        MaxAwaitTime *time.Duration
        MaxTime *time.Duration
        Min interface{}
        NoCursorTimeout *bool
        OplogReplay *bool
        Projection interface{}
        ReturnKey *bool
        ShowRecordID *bool
        Skip *int64
        Snapshot *bool
        Sort interface{}
    }
// db.collection.insertOne() 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 one document
let commandResult = await customerCollection.insertOne({
  name: "john doe",
  age: 34,
});

console.log(
  'Command: db.customer.insertOne({name: "john doe", age: 34}) | Result: ',
  commandResult
);

// Insert document with _id defined
commandResult = await customerCollection.insertOne({
  _id: 99,
  name: "Leatha Ledner",
  age: 54,
});

console.log(
  'Command: db.customer.insertOne({_id: 99, name: "Leatha Ledner", age: 54}) | Result: ',
  commandResult
);

// Try to add a document with an existing _id
// We get an error
try {
  commandResult = await customerCollection.insertOne({
    _id: 99,
    name: "Sophia Gray",
    age: 25,
  });

  console.log(
    'Command: db.customer.insertOne({_id: 99, name: "Sophia Gray", age: 25}) | Result: ',
    commandResult
  );
} catch (err) {
  console.log(
    'Command: db.customer.insertOne({_id: 99, name: "Sophia Gray", age: 25}) | Error: ',
    err
  );
}

// Provide writeConcern to insertOne
commandResult = await customerCollection.insertOne(
  {
    _id: 100,
    name: "Sophia Gray",
    age: 25,
  },
  { writeConcern: { w: "majority", wtimeout: 100 } }
);

console.log(
  'Command: db.customer.insertOne({_id: 100, name: "Sophia Gray", age: 25}, {writeConcern: {w: "majority", wtimeout: 100}}}) | Result: ',
  commandResult
);

// Insert nested document
commandResult = await customerCollection.insertOne({
  name: "Devonte Greenholt",
  dob: new Date("1976-01-12T06:00:00Z"),
  address: {
    street: "1114 Edmonton Trail NE",
    city: "Calgary",
    state: "Alberta",
    zip: "T2E 0Z2",
    phone: "(403) 277-3408",
    country: "canada",
  },
});

console.log(
  'Command: db.customer.insertOne(name: "Devonte Greenholt", dob: ISODate("1976-01-12T06:00:00Z"), address: { street: "1114 Edmonton Trail NE", city: "Calgary", state: "Alberta", zip: "T2E 0Z2", phone: "(403) 277-3408", country: "canada"}) | Result: ',
  commandResult
);

// Close connection
await mongo.close();

process.exit(0);

Output:

Command: db.customer.insertOne({name: "john doe", age: 34}) | Result:  {
  acknowledged: true,
  insertedId: new ObjectId('65c71402fdaf589fd55a18c5')
}

Command: db.customer.insertOne({_id: 99, name: "Leatha Ledner", age: 54}) | Result:  { acknowledged: true, insertedId: 99 }

Command: db.customer.insertOne({_id: 99, name: "Sophia Gray", age: 25}) | Error:  MongoServerError: E11000 duplicate key error collection: bigboxcode.customer index: _id_ dup key: { _id: 99 }
    at InsertOneOperation.execute (...node_modulesmongodbliboperationsinsert.js:48:19)   
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async executeOperationAsync (...node_modulesmongodbliboperationsexecute_operation.js:106:16)
    at async file:///.../insert-one.js:42:19 {
  index: 0,
  code: 11000,
  keyPattern: { _id: 1 },
  keyValue: { _id: 99 },
  [Symbol(errorLabels)]: Set(0) {}
}

Command: db.customer.insertOne({_id: 100, name: "Sophia Gray", age: 25}, {writeConcern: {w: "majority", wtimeout: 100}}}) | Result:  { acknowledged: true, insertedId: 100 }

Command: db.customer.insertOne(name: "Devonte Greenholt", dob: ISODate("1976-01-12T06:00:00Z"), address: { street: "1114 Edmonton Trail NE", city: "Calgary", state: "Alberta", zip: "T2E 0Z2", phone: "(403) 277-3408", country: "canada"}) | Result:  {
  acknowledged: true,
  insertedId: new ObjectId('65c71402fdaf589fd55a18c6')
}

NOTES

  • Use NodeJS “insertOne()” method from the package “mongodb“.
  • Method signatures are-
    • insertOne(doc: OptionalUnlessRequiredId<TSchema>, options?: InsertOneOptions): Promise<InsertOneResult<TSchema>>
# db.collection.insertOne() 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 one document
commandResult = customer_collection.insert_one({
  "name": "john doe",
  "age": 34,
})

print("Command: db.customer.insertOne({name: "john doe", age: 34}) | Result: ", commandResult)


# Insert document with _id defined
commandResult = customer_collection.insert_one({
  "_id": 99,
  "name": "Leatha Ledner",
  "age": 54,
})

print("Command: db.customer.insertOne({_id: 99, name: "Leatha Ledner", age: 54}) | Result: ", commandResult)


# Try to add a document with an existing _id
# We get an error
try:
  commandResult = customer_collection.insert_one({
    "_id": 99,
    "name": "Sophia Gray",
    "age": 25,
  })

  print("Command: db.customer.insertOne({_id: 99, name: "Sophia Gray", age: 25}) | Result: ", commandResult)
except Exception as error:
  print("Command: db.customer.insertOne({_id: 99, name: "Sophia Gray", age: 25}) | Error: ", error)
  

# Provide writeConcern to insertOne
commandResult = customer_collection.with_options(write_concern=WriteConcern(w=1, wtimeout= 100)).insert_one(
  {
    "_id": 100,
    "name": "Sophia Gray",
    "age": 25,
  }
)

print("Command: db.customer.insertOne({_id: 100, name: "Sophia Gray", age: 25}, {writeConcern: {w: "majority", wtimeout: 100}}}) | Result: ", commandResult)


# Insert nested document
commandResult = customer_collection.insert_one({
  "name": "Devonte Greenholt",
  "dob": datetime.strptime("1976-01-12T06:00:00Z", "%Y-%m-%dT%H:%M:%SZ"),
  "address": {
    "street": "1114 Edmonton Trail NE",
    "city": "Calgary",
    "state": "Alberta",
    "zip": "T2E 0Z2",
    "phone": "(403) 277-3408",
    "country": "canada",
  },
})

print("Command: db.customer.insertOne(name: "Devonte Greenholt", dob: ISODate("1976-01-12T06:00:00Z"), address: { street: "1114 Edmonton Trail NE", city: "Calgary", state: "Alberta", zip: "T2E 0Z2", phone: "(403) 277-3408", country: "canada"}) | Result: ", commandResult)


# Close connection
mongo_client.close()

Output:

Command: db.customer.insertOne({name: "john doe", age: 34}) | Result:  InsertOneResult(ObjectId('65c87df59ef77a12730effed'), acknowledged=True)

Command: db.customer.insertOne({_id: 99, name: "Leatha Ledner", age: 54}) | Result:  InsertOneResult(99, acknowledged=True)

Command: db.customer.insertOne({_id: 99, name: "Sophia Gray", age: 25}) | Error:  E11000 duplicate key error collection: bigboxcode.customer index: _id_ dup key: { _id: 99 }, full error: {'index': 0, 'code': 11000, 'errmsg': 'E11000 duplicate key error collection: bigboxcode.customer index: _id_ dup key: { _id: 99 }', 'keyPattern': {'_id': 1}, 'keyValue': {'_id': 99}}

Command: db.customer.insertOne({_id: 100, name: "Sophia Gray", age: 25}, {writeConcern: {w: "majority", wtimeout: 100}}}) | Result:  InsertOneResult(100, acknowledged=True)

Command: db.customer.insertOne(name: "Devonte Greenholt", dob: ISODate("1976-01-12T06:00:00Z"), address: { street: "1114 Edmonton Trail NE", city: "Calgary", state: "Alberta", zip: "T2E 0Z2", phone: "(403) 277-3408", country: "canada"}) | Result:  InsertOneResult(ObjectId('65c87df59ef77a12730effee'), acknowledged=True)

NOTES

  • Use method “insert_one” from redis-py.
  • Signature of the method is –
    • def insert_one(
              self,
              document: Union[_DocumentType, RawBSONDocument],
              bypass_document_validation: bool = False,
              session: Optional[ClientSession] = None,
              comment: Optional[Any] = None,
      ) -> InsertOneResult
// db.collection.insertOne() method example in Java

import com.mongodb.client.*;
import org.bson.Document;

public class InsertOne {

    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 one document
            Document document1 = new Document("name", "john doe")
                    .append("age", 34);
            customerCollection.insertOne(document1);
            System.out.println("Command: db.customer.insertOne({name: "john doe", age: 34}) | Result: " + document1);

            // Insert document with _id defined
            Document document2 = new Document("_id", 99)
                    .append("name", "Leatha Ledner")
                    .append("age", 54);
            customerCollection.insertOne(document2);
            System.out.println("Command: db.customer.insertOne({_id: 99, name: "Leatha Ledner", age: 54}) | Result: " + document2);

            // Try to add a document with an existing _id
            // We get an error
            try {
                Document document3 = new Document("_id", 99)
                        .append("name", "Sophia Gray")
                        .append("age", 25);
                customerCollection.insertOne(document3);
                System.out.println("Command: db.customer.insertOne({_id: 99, name: "Sophia Gray", age: 25}) | Result: " + document3);
            } catch (Exception e) {
                System.out.println("Command: db.customer.insertOne({_id: 99, name: "Sophia Gray", age: 25}) | Error: " + e);
            }

            // Provide writeConcern to insertOne
            Document document4 = new Document("_id", 100)
                    .append("name", "Sophia Gray")
                    .append("age", 25);
            customerCollection.insertOne(document4);
            System.out.println("Command: db.customer.insertOne({_id: 100, name: "Sophia Gray", age: 25}, {writeConcern: {w: "majority", wtimeout: 100}}}) | Result: " + document4);

            // Insert nested document
            Document document5 = new Document("name", "Devonte Greenholt")
                    .append("dob", "1976-01-12T06:00:00Z")
                    .append("address", new Document("street", "1114 Edmonton Trail NE")
                            .append("city", "Calgary")
                            .append("state", "Alberta")
                            .append("zip", "T2E 0Z2")
                            .append("phone", "(403) 277-3408")
                            .append("country", "canada"));
            customerCollection.insertOne(document5);
            System.out.println("Command: db.customer.insertOne(name: "Devonte Greenholt", dob: ISODate("1976-01-12T06:00:00Z"), address: { street: "1114 Edmonton Trail NE", city: "Calgary", state: "Alberta", zip: "T2E 0Z2", phone: "(403) 277-3408", country: "canada"}) | Result: " + document5);

            // Close connection
            mongoClient.close();
        }
    }
}

Output:

Command: db.customer.insertOne({name: "john doe", age: 34}) | Result: Document{{name=john doe, age=34, _id=65c8b52d48356a2730e4ca1e}}

Command: db.customer.insertOne({_id: 99, name: "Leatha Ledner", age: 54}) | Result: Document{{_id=99, name=Leatha Ledner, age=54}}

Command: db.customer.insertOne({_id: 99, name: "Sophia Gray", age: 25}) | Error: com.mongodb.MongoWriteException: Write operation error on server localhost:27017. Write error: WriteError{code=11000, message='E11000 duplicate key error collection: bigboxcode.customer index: _id_ dup key: { _id: 99 }', details={}}.

Command: db.customer.insertOne({_id: 100, name: "Sophia Gray", age: 25}, {writeConcern: {w: "majority", wtimeout: 100}}}) | Result: Document{{_id=100, name=Sophia Gray, age=25}}

Command: db.customer.insertOne(name: "Devonte Greenholt", dob: ISODate("1976-01-12T06:00:00Z"), address: { street: "1114 Edmonton Trail NE", city: "Calgary", state: "Alberta", zip: "T2E 0Z2", phone: "(403) 277-3408", country: "canada"}) | Result: Document{{name=Devonte Greenholt, dob=1976-01-12T06:00:00Z, address=Document{{street=1114 Edmonton Trail NE, city=Calgary, state=Alberta, zip=T2E 0Z2, phone=(403) 277-3408, country=canada}}, _id=65c8b52d48356a2730e4ca1f}}

NOTES

  • Use the method “iinsertOne()” from MongoCollection.
  • Signatures of the method are-
    • InsertOneResult insertOne(TDocument document)
    • InsertOneResult insertOne(TDocument document, InsertOneOptions options)
    • InsertOneResult insertOne(ClientSession clientSession, TDocument document)
    • InsertOneResult insertOne(ClientSession clientSession, TDocument document, InsertOneOptions options)

Source Code

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

Related Methods

CommandDetails
db.collection.updateMany() Method Details
db.collection.insertMany() Method Details
db.collection.bulkWrite() Method Details

Leave a Comment


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