DEV Community

Full Stack Hacker
Full Stack Hacker

Posted on • Edited on

1 1

Adding data to a MongoDB database (part 1)

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.

Example:

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

Insert a document without an _id field example:

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

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

Insert a document with an _id field example:

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

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:

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay