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.
Section overview
5 resourcesExplores 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()andinsertMany()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
-
Exercise: Insert a single document into a 'products' collection with the fields: productName, price, and category.
-
Exercise: Insert multiple documents into a 'orders' collection. Each document should have the fields: orderId, customerId, and totalAmount.
Solutions
- 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");
});
- 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.
Related topics
Keep learning with adjacent tracks.
Popular tools
Helpful utilities for quick tasks.
Random Password Generator
Create secure, complex passwords with custom length and character options.
Use toolLatest articles
Fresh insights from the CodiWiki team.
AI in Drug Discovery: Accelerating Medical Breakthroughs
In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…
Read articleAI in Retail: Personalized Shopping and Inventory Management
In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …
Read articleAI 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 articleAI 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 articleAI in Legal Compliance: Ensuring Regulatory Adherence
In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…
Read article