Ticker

6/recent/ticker-posts

Insert Single Document in MongoDB

Insert Single Document in MongoDB

Heading: Introduction

MongoDB is a popular NoSQL database that stores data in a JSON-like format called BSON (Binary JSON). One of the basic operations in MongoDB is inserting a single document into a collection. In this documentation, we will explain how to perform this operation using various programming languages, along with appropriate code examples and explanations.

Subheading: Prerequisites

Before you proceed with the examples, make sure you have the following in place:

  1. MongoDB installed on your system or accessible through a cloud service.
  2. A MongoDB driver installed for the programming language you want to use (e.g., pymongo for Python, MongoDB driver for Node.js, etc.).

Subheading: Python Example

Python is a popular programming language with a well-supported MongoDB driver called pymongo. Below is an example of how to insert a single document into MongoDB using Python:

python
import pymongo

# Connect to MongoDB
client = pymongo.MongoClient("mongodb://localhost:27017/")

# Access the desired database and collection
db = client["mydatabase"]
collection = db["mycollection"]

# Data to be inserted as a dictionary
data = {
"name": "John Doe",
"age": 30,
"email": "john@example.com"
}

# Insert the document into the collection
inserted_document = collection.insert_one(data)

# Print the inserted document's ID
print("Inserted document ID:", inserted_document.inserted_id)

Explanation:

  1. We first import the pymongo library to work with MongoDB in Python.
  2. Create a MongoClient instance and connect to the MongoDB server running on localhost at the default port 27017.
  3. Access the desired database (mydatabase) and collection (mycollection) where we want to insert the document.
  4. Create a dictionary (data) containing the key-value pairs representing the document's data.
  5. Use the insert_one() method to insert the document into the collection. It returns an InsertOneResult object that contains the ID of the inserted document.
  6. Finally, we print the ID of the inserted document.

Subheading: Node.js Example

Node.js is a popular JavaScript runtime that can be used to interact with MongoDB using its official MongoDB driver. Below is an example of how to insert a single document into MongoDB using Node.js:

javascript
const { MongoClient } = require('mongodb');

// MongoDB connection URL
const url = 'mongodb://localhost:27017';

// Database and collection names
const dbName = 'mydatabase';
const collectionName = 'mycollection';

// Data to be inserted as an object
const data = {
name: 'Jane Smith',
age: 25,
email: 'jane@example.com'
};

// Connect to MongoDB
MongoClient.connect(url, { useUnifiedTopology: true })
.then(client => {
const db = client.db(dbName);
const collection = db.collection(collectionName);

// Insert the document into the collection
collection.insertOne(data)
.then(result => {
console.log('Inserted document ID:', result.insertedId);
})
.catch(error => {
console.error('Error inserting document:', error);
})
.finally(() => {
client.close();
});
})
.catch(error => {
console.error('Error connecting to MongoDB:', error);
});

Explanation:

  1. We import the MongoClient class from the 'mongodb' module to interact with MongoDB.
  2. Define the MongoDB connection URL, database name (mydatabase), and collection name (mycollection).
  3. Create an object (data) with the key-value pairs representing the document's data.
  4. Establish a connection to MongoDB using MongoClient.connect(). We use useUnifiedTopology: true option for the new MongoDB driver.
  5. Access the desired database and collection using the client object.
  6. Use the insertOne() method to insert the document into the collection. It returns a promise that resolves to an object containing the ID of the inserted document.
  7. Print the ID of the inserted document in the then block, and handle errors in the catch block.
  8. Finally, close the MongoDB connection.

Subheading: Conclusion

Congratulations! You have learned how to insert a single document into MongoDB using Python and Node.js. This fundamental operation is the building block for more complex database interactions in MongoDB. Make sure to explore other MongoDB CRUD operations to enhance your database skills further.

    Post a Comment

    0 Comments