MongoDB / CRUD Operations in MongoDB

Inserting Documents into MongoDB

In this tutorial, we will cover how to insert documents into MongoDB. You will learn how to add new data to your database, using both the insertOne and insertMany methods.

Tutorial 1 of 5 5 resources in this section

Section overview

5 resources

Explores how to create, read, update, and delete documents in MongoDB.

1. Introduction

Tutorial's Goal

This tutorial aims to guide you through the process of inserting documents into MongoDB, a popular NoSQL database. We will explore the usage of both the insertOne() and insertMany() methods.

Learning Outcome

By the end of this tutorial, you will be able to:

  • Understand how to insert documents into MongoDB
  • Use the insertOne() and insertMany() methods in MongoDB
  • Understand the structure of documents in MongoDB

Prerequisites

  • Basic knowledge of JavaScript
  • MongoDB installed on your local machine

2. Step-by-Step Guide

Concepts

In MongoDB, data is stored in BSON documents, which are binary representations of JSON-like documents. When you insert data into MongoDB, you're essentially inserting these documents into collections.

The insertOne() method is used to insert a single document into a collection, while insertMany() is used to insert multiple documents at once.


Example: insertOne()

let myDocument = { name: "John", age: 30, city: "New York" };

db.collection('users').insertOne(myDocument, function(err, res) {
  if (err) throw err;
  console.log("Document inserted");
});

In the code above, we create an object myDocument to represent our document. This object is then passed as an argument to the insertOne() method. If the operation is successful, "Document inserted" will be logged to the console.


Example: insertMany()

let myDocuments = [
  { name: "John", age: 30, city: "New York" },
  { name: "Jane", age: 25, city: "Chicago" },
  { name: "Jim", age: 35, city: "Boston" }
];

db.collection('users').insertMany(myDocuments, function(err, res) {
  if (err) throw err;
  console.log("Documents inserted: " + res.insertedCount);
});

In this example, myDocuments is an array of objects, each representing a document. The insertMany() method inserts all these documents into the collection. If successful, it prints the number of documents inserted.


3. Code Examples

Example: Insert a Single Document

let user = { name: "Alice", age: 22, city: "Los Angeles" };

db.collection('users').insertOne(user, function(err, res) {
  if (err) throw err;
  console.log("Document inserted");
  console.log(res.ops); // Prints the inserted document
});

In this script, we insert a document into the 'users' collection. res.ops contains the document that was inserted.

Example: Insert Multiple Documents

let users = [
  { name: "Bob", age: 27, city: "Seattle" },
  { name: "Charlie", age: 32, city: "Houston" },
  { name: "David", age: 45, city: "San Francisco" }
];

db.collection('users').insertMany(users, function(err, res) {
  if (err) throw err;
  console.log("Number of documents inserted: " + res.insertedCount);
});

This script inserts multiple documents into the 'users' collection and prints the number of documents inserted.


4. Summary

In this tutorial, we've learned how to insert documents into MongoDB using the insertOne() and insertMany() methods.

Next steps for learning could include understanding how to query, update and delete documents in MongoDB. You might also want to explore the MongoDB Node.js Driver documentation for more advanced features.


5. Practice Exercises

  1. Exercise: Insert a single document into a 'products' collection with the fields: productName, price, and category.

  2. Exercise: Insert multiple documents into a 'orders' collection. Each document should have the fields: orderId, customerId, and totalAmount.

Solutions

  1. Solution:
let product = { productName: "Apple", price: 1.5, category: "Fruits" };

db.collection('products').insertOne(product, function(err, res) {
  if (err) throw err;
  console.log("Document inserted");
});
  1. Solution:
let orders = [
  { orderId: "001", customerId: "123", totalAmount: 100 },
  { orderId: "002", customerId: "456", totalAmount: 200 }
];

db.collection('orders').insertMany(orders, function(err, res) {
  if (err) throw err;
  console.log("Number of documents inserted: " + res.insertedCount);
});

In the first solution, we create a product document and insert it into the 'products' collection. In the second solution, we create an array of order documents and insert them into the 'orders' collection.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

XML Sitemap Generator

Generate XML sitemaps for search engines.

Use tool

CSV to JSON Converter

Convert CSV files to JSON format and vice versa.

Use tool

Random String Generator

Generate random alphanumeric strings for API keys or unique IDs.

Use tool

Base64 Encoder/Decoder

Encode and decode Base64 strings.

Use tool

Unit Converter

Convert between different measurement units.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help