MongoDB Tutorial

  • Home
  • Getting Started
  • CRUD
  • Indexes
Home / MongoDB CRUD / MongoDB insertOne

MongoDB insertOne

Summary: in this tutorial, you will learn how to use the MongoDB insertOne() method to insert a single document into a collection.

Introduction to MongoDB insertOne() method

The insertOne() method allows you to insert a single document into a collection.

The insertOne() method has the following syntax:

db.collection.insertOne( <document>, { writeConcern: <document>} )

The insertOne() method accepts two arguments:

  • document is a document that you want to insert into the collection. The document argument is required.
  • writeConcern is an optional argument that describes the level of acknowledgment requested from MongoDB for insert operation to a standalone MongoDB server or to shared clusters. We’ll discuss the writeConcern another tutorial.

The insertOne() method returns a document that contains the following fields:

  • acknowledged is a boolean value. It is set to true if the insert executed with write concern or false if the write concern was disabled.
  • insertedId stores the value of _id field of the inserted document.

Note that if the collection does not exist, the insertOne() method will also create the collection and insert the document into it.

If you don’t specify the _id field in the document, MongoDB will add the _id field and generate a unique ObjectId for it before insert.

If you explicitly specify a value for the _id field, you need to ensure that it is unique in the collection. Otherwise, you will get a duplicate key error.

To insert multiple documents into a collection, you use the insertMany() method.

MongoDB insertOne() method examples

First, you need to launch the mongo shell and connect to the bookdb database:

mongo bookdb

1) Insert a document without an _id field example

The following example uses the insertOne() method to insert a new document into the books collection:

db.books.insertOne({ title: 'MongoDB insertOne', isbn: '0-7617-6154-3' });

Output:

{ "acknowledged" : true, "insertedId" : ObjectId("5f31cf00902f22de3464ddc4") }

In this example, we passed a document to the insertOne() method without specifying the _id field, therefore, MongoDB automatically added the _id field and assigned it a unique ObjectId value.

Note that you will see a different ObjectId value from this example because ObjectId values are specific to machine and time when the insertOne() method executes.

To select the document that you have inserted, you can use the find() method like this:

db.books.find().pretty()

Output:

{ "_id" : ObjectId("5f31cf00902f22de3464ddc4"), "title" : "MongoDB insertOne", "isbn" : "0-7617-6154-3" }

2) Insert a document with an _id field example

The following example uses the insertOne() method to insert a document that has an _id field into the books collection:

db.books.insertOne({ _id: 1, title: "Mastering Big Data", isbn: "0-9270-4986-4" });

Output:

{ "acknowledged" : true, "insertedId" : 1 }

The following example attempts to insert another document whose _id field already exists into the books collection:

db.books.insertOne({ _id: 1, title: "MongoDB for JS Developers", isbn: "0-4925-3790-9" });

Since the _id: 1 already exists, MongoDB threw the following exception:

WriteError({ "index" : 0, "code" : 11000, "errmsg" : "E11000 duplicate key error collection: bookstore.books index: _id_ dup key: { _id: 1.0 }", "op" : { "_id" : 1, "title" : "MongoDB for JS Developers", "isbn" : "0-4925-3790-9" } })

Summary

  • Use db.collection.insertOne() method to insert a single document into a collection.
  • If you explicitly provide a value for the _id field, you must ensure that the value is unique within the collection or you will get a duplicate key error.
  • Was this tutorial helpful ?
  • YesNo
Next MongoDB insertMany

Getting Started

  • What is MongoDB
  • Install MongoDB
  • MongoDB Basics
  • MongoDB Shell
  • MongoDB Data Types

Inserting Documents

  • insertOne
  • insertMany
  • mongoimport

Selecting Documents

  • findOne
  • find
  • Projection: Selecting Returned Fields

Comparison Query Operators

  • $eq: Equal To Operator
  • $lt: Less Than Operator
  • $lte: Less Than or Equal To Operator
  • $gt: Greater Than Operator
  • $gte: Greater Than or Equal To Operator
  • $ne: Not Equal To Operator
  • $in: In Operator
  • $nin: Not In Operator

Logical Query Operators

  • $and: Logical AND Opeartor
  • $or: Logical OR Operator
  • $not: Logical NOT Operator
  • $nor: Logical NOR Operator

Element Query Operators

  • $exists
  • $type

Array Query Operators

  • $size
  • $all
  • $elemMatch

Sorting & Limiting

  • sort(): Sorting documents
  • limit(): Limiting documents

Updating Documents

  • updateOne: Update one Document
  • updateMany: Update Multiple Documents
  • $inc: Increase / Decrease Field Value
  • $min: Update Field Value
  • $max: Update Field Value
  • $mul: Mutiply Field By a Number
  • $unset: Remove Fields
  • $rename: Rename Fields
  • Upsert

Deleting Documents

  • deleteOne
  • deleteMany

About MongoDBTutorial.com

This MongoDB Tutorial helps you master MongoDB quickly.

Recent Tutorials

  • MongoDB Indexes
  • MongoDB limit
  • MongoDB sort
  • MongoDB Upsert
  • MongoDB Projection

Site Links

  • Home
  • Contact
  • About
  • Privacy Policy

Copyright © 2021 ยท By mongodbtutorial.org. All Rights Reserved.