Inserting Documents in MongoDB

Introduction

Hello there! This lesson covers an essential aspect of working with MongoDB: inserting documents into MongoDB collections. The ability to add data to your database is fundamental for any application. Let’s dive into MongoDB’s data insertion mechanisms and explore the structure of the documents you will be inserting.

Two Ways to Insert Data

MongoDB offers two primary methods to insert data into collections:

  1. insertOne(): Inserts a single document into a collection.

    db.collection.insertOne(document)
  2. insertMany(): Inserts multiple documents into a collection.

    db.collection.insertMany([document1, document2, ...])

Inserting a Single Document

Using the insertOne() method, you can add a single document to a collection. Here is an example where we insert a single book into the books collection:

use library_db

db.books.insertOne({
  title: "1984",
  author: { 
    name: "George Orwell", 
    nationality: "British"
  },
  published_year: 1949,
  genre: "Dystopian",
  publisher: {
    name: "Secker & Warburg",
    location: "London"
  }
})

In this example, the command db.books.insertOne() inserts the specified document into the books collection.

Inserting Multiple Documents

To add multiple documents at once, you can use the insertMany() method, which requires an array of documents as its parameter. Below is an example that inserts two books into the books collection:

use library_db

db.books.insertMany([
  {
    title: "The Great Gatsby",
    author: {
      name: "F. Scott Fitzgerald",
      nationality: "American"
    },
    published_year: 1925,
    genre: "Fiction",
    publisher: {
      name: "Scribner",
      location: "New York"
    }
  },
  {
    title: "Moby Dick",
    author: {
      name: "Herman Melville",
      nationality: "American"
    },
    published_year: 1851,
    genre: "Adventure",
    publisher: {
      name: "Harper & Brothers",
      location: "New York"
    }
  }
])

In this example, the insertMany() method is used to insert an array of document objects, where each object represents a book. This command adds both books to the books collection. Note that this function accepts an array of documents, denoted by the square brackets [].

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal