0% found this document useful (0 votes)
13 views27 pages

WT Unit 4

The document provides an overview of Java Beans and Enterprise JavaBeans (EJBs), detailing their conventions, types, and uses in software development. It also introduces Node.js, its features, and how to set up a development environment, including the use of npm for package management. Additionally, it covers the REPL terminal for testing JavaScript code interactively.

Uploaded by

ashmakhan8855
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views27 pages

WT Unit 4

The document provides an overview of Java Beans and Enterprise JavaBeans (EJBs), detailing their conventions, types, and uses in software development. It also introduces Node.js, its features, and how to set up a development environment, including the use of npm for package management. Additionally, it covers the REPL terminal for testing JavaScript code interactively.

Uploaded by

ashmakhan8855
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

Unit 4

A Java Bean is a reusable software component that follows certain conventions in the Java
programming language. It is a class that encapsulates multiple objects into a single object (a
bean). Java Beans can be used in a variety of contexts, such as GUI components, business logic,
or enterprise applications. They are particularly useful for representing data and for enabling
the separation of concerns in software design.
To be considered a Java Bean, a class must adhere to the following simple conventions:
1. Private Member Variables: The fields (attributes) of a Java Bean should be private to
promote encapsulation.
2. Public Constructors: It must have a no-argument constructor, which allows easy
instantiation of the Bean.
3. Getter and Setter Methods: It must provide public methods to get and set the values of
its private member variables. These methods are typically called "getters" and "setters"
and are named following a specific pattern.
4. Serializable: A Java Bean must implement the Serializable interface to support
persistence and allow it to be easily transferred over networks or saved to a file.
Java Beans are typically used in Java-based frameworks like Java EE, Spring, and JavaFX where
the beans can be managed and interacted with in various ways.
Java Bean Properties
Java Bean properties are the fields or attributes of a Java Bean class. These properties are
generally encapsulated by private instance variables, and access to them is provided through
getter and setter methods. The properties allow the encapsulation of data and the flexibility of
controlling how the data is accessed or modified.
There are two types of properties in Java Beans:
Simple Properties: These represent a single value (like an int, String, double, boolean, etc.). For
example, a name property in a Person bean.
public class Person{
private String name;
private int age;
public String getName() {
return name; }
public void setName(String name) {
this.name = name;
public int getAge() {
return age; }
public void setAge(int age) {
this.age = age; }}
Indexed Properties: These allow access to a property using an index, usually for handling
collections like arrays or lists within a bean. For example, a Person bean might have a list of
phone numbers.
public class Person implements Serializable {
private List<String> phoneNumbers = new ArrayList<>();
public String getPhoneNumber(int index) {
return phoneNumbers.get(index); }
public void setPhoneNumber(int index, String phoneNumber) {
phoneNumbers.set(index, phoneNumber); }
public int getPhoneNumbersCount() {
return phoneNumbers.size(); }}
In the context of Enterprise JavaBeans (EJBs), there are three primary types of beans: Stateful
Session Beans, Stateless Session Beans, and Entity Beans. Each type serves a different purpose
in enterprise applications, particularly when handling business logic and data persistence.
Below is a detailed explanation of each type:
Stateful Session Bean
A Stateful Session Bean (SFSB) is an EJB that maintains the state of a client across multiple
method invocations. The state is specific to a client and persists for the duration of a session
with that client. This means the server retains the state of the bean for the client between
method calls, allowing the client to interact with the bean in a way that the bean "remembers"
previous interactions.
Client-Specific State: A Stateful Session Bean stores state information between method
invocations for a specific client.
Lifecycle: The bean exists for the duration of the client’s session. It is created when the client
first interacts with it and destroyed when the session ends (either through explicit removal or
timeout).
Serialization: The state of a Stateful Session Bean is often serialized when it is moved between
servers or stored for persistence purposes.
@Stateful
public class ShoppingCartBean implements ShoppingCartRemote {
private List<String> items = new ArrayList<>();
@Override
public void addItem(String item) {
items.add(item); }
@Override
public List<String> getItems() {
return items; }
@Override
public void checkout() {
// Checkout process
items.clear();
}}
Stateless Session Bean
A Stateless Session Bean (SLSB) is an EJB that does not maintain any client-specific state. Each
method invocation is independent, and the bean can be used by multiple clients without
retaining any information between method calls. A Stateless Session Bean can serve any client,
and it does not remember previous interactions.
No Client-Specific State: Stateless Session Beans do not hold any state information between
method calls. Each call to the bean is independent.
Lifecycle: Stateless beans do not have a specific client session. They are created and destroyed
by the container as needed to serve incoming requests. The container may pool instances of
Stateless Beans for reuse.
@Stateless
public class AccountServiceBean implements AccountServiceRemote {
@Override
public void transferMoney(Account from, Account to, double amount) {
from.withdraw(amount);
to.deposit(amount); }}
Entity Bean
An Entity Bean is a type of EJB that represents persistent data, typically mapped to a row in a
database table. Entity Beans are used to interact with databases in a Java EE application. They
allow an object-oriented way to model and manage database records.
public class ProductBean {
private String productId;
private String name;
private double price;
public void setProductId(String productId) {
this.productId = productId;
}
public String getProductId() {
return productId;
}
// Persistence logic...
}

Enterprise JavaBeans (EJB) Types

Enterprise JavaBeans (EJBs) are server-side components that are part of the Jakarta EE
(formerly Java EE) specification. They provide a simplified model for building distributed,
transactional, and multi-user enterprise applications. EJBs manage business logic and handle
things like security, transactions, concurrency, and messaging.

@Stateful
public class ShoppingCartBean implements ShoppingCartRemote {
private List<String> items = new ArrayList<>();
@Override
public void addItem(String item) {
items.add(item); }
@Override
public List<String> getItems() {
return items; }
@Override
public void checkout() {
// Process checkout logic
items.clear(); }}
Message-Driven Bean (MDB)
A Message-Driven Bean is used for asynchronous message processing. It listens to a message
queue (e.g., JMS) and processes messages asynchronously.

 Can be used to receive and process messages from queues or topics.


 Provides a way to decouple components and create scalable, event-driven applications.
 Typically used for handling background tasks or processing incoming events
asynchronously.
@MessageDriven
public class OrderProcessingBean implements MessageListener {
@Override
public void onMessage(Message message) {
// Process order message asynchronously
}}
Node Js
Node.js is a powerful, event-driven, non-blocking, and asynchronous runtime environment that
allows developers to run JavaScript on the server side. It is built on Chrome's V8 JavaScript
engine and is primarily used for building scalable network applications, web servers, and real-
time applications. Node.js provides an event-driven, non-blocking I/O model that makes it
efficient and lightweight for handling concurrent requests, especially in applications that
require handling many simultaneous connections, such as chat applications, live data feeds, or
real-time communication systems.
Node.js is an open-source, cross-platform runtime environment for executing JavaScript code
outside of a browser. It uses the V8 JavaScript engine (the same engine that runs JavaScript in
Chrome) to interpret and execute code. Node.js allows JavaScript to be used for backend
development, which was traditionally dominated by languages like Python, Ruby, Java, and
PHP.

JavaScript Engine (V8): V8 is an open-source JavaScript engine developed by Google. It


compiles JavaScript directly into native machine code for faster execution.
Libuv: Node.js uses the libuv library for handling asynchronous I/O operations like networking,
file system access, and child process management.
Event Loop: Node.js uses an event-driven, non-blocking I/O model where tasks are handled
asynchronously, using a single thread.
npm (Node Package Manager): npm is the default package manager for Node.js, which allows
developers to share, install, and manage third-party libraries and dependencies.
Core Features of Node.js
Non-blocking, Asynchronous I/O:
Non-blocking: Node.js operations do not block the execution of subsequent code. This is critical
for building scalable applications that handle many simultaneous I/O operations (e.g., database
queries, file access, API calls).
Asynchronous: Functions in Node.js are executed asynchronously using callbacks, promises, or
async/await, which allow Node.js to process multiple requests concurrently without waiting for
each task to finish.
Single-threaded Event Loop:
Node.js runs in a single-threaded event loop model, which is optimized to handle many
concurrent connections without the need to spawn multiple threads. Instead of blocking
operations, the event loop processes tasks in an efficient manner, allowing high concurrency.
The event loop runs continuously, waiting for tasks like incoming requests, file operations, or
network responses. When these tasks are completed, the event loop invokes callbacks to
handle them.
V8 JavaScript Engine:
Node.js uses Google Chrome's V8 engine, which compiles JavaScript code directly to machine
code rather than interpreting it. This makes Node.js applications very fast and efficient.
Cross-platform:
Node.js is cross-platform, which means it runs on various operating systems, including
Windows, macOS, and Linux. This gives developers flexibility to build applications that work on
multiple platforms.
Scalability:
Node.js supports scaling both vertically (by adding more resources to a single machine) and
horizontally (by distributing the load across multiple machines). It is well-suited for building
real-time applications, like chat applications, that require high concurrency and scalability.
Built-in Libraries:
Node.js comes with a variety of built-in libraries for handling common tasks, such as file system
operations, HTTP requests, networking, events, and streams. These libraries make it easier to
perform everyday tasks in Node.js applications.
npm (Node Package Manager):
npm is the package manager that ships with Node.js. It allows developers to install and manage
third-party packages and libraries for their projects. With a massive collection of open-source
packages, npm simplifies the development process and speeds up coding.
How Node.js Works
Node.js uses an event-driven, non-blocking I/O model, which is the key to its performance and
scalability. Here’s how it works:
Event Loop:
The event loop is the core mechanism behind Node.js's asynchronous behavior. It continuously
monitors the system for tasks that need to be processed, such as I/O requests, database
queries, or client requests.
Callback Queue:
When an I/O operation (e.g., reading a file, making a network request) is triggered, Node.js
doesn’t wait for it to complete before continuing with other tasks. Instead, it registers a
callback function to be executed once the I/O operation finishes. This callback function is placed
in the callback queue.
Event Loop Phases: The event loop has several phases through which it processes tasks:
Timers: Executes callbacks scheduled by setTimeout() and setInterval().
I/O Callbacks: Executes most of the callbacks, such as those for file system operations or
network requests.
Idle, Prepare: Internal Node.js tasks.
Poll: Retrieves new I/O events; executes callbacks for those I/O events.
Check: Executes callbacks scheduled by setImmediate().
Close Callbacks: Executes when closing resources, such as a socket or file descriptor.
Non-blocking I/O:

While an I/O operation is being performed, Node.js doesn’t block the execution of other tasks.
Instead, it registers the callback function to handle the result of the operation once it
completes, enabling asynchronous processing.
Environment Setup for Node.js Development
Setting up a development environment for Node.js is a crucial step to get started with building
applications using Node.js. This process involves installing the necessary software, setting up
development tools, and configuring your system for optimal productivity.

Before you begin setting up Node.js on your machine, ensure the following prerequisites are
met:

 Internet Connection: Required to download Node.js and its associated tools.


 Basic Knowledge of JavaScript: Node.js is based on JavaScript, so having a basic
understanding of the language will be helpful.
 Text Editor/IDE: A good text editor like Visual Studio Code (VS Code), Sublime Text, or
Atom is needed for writing and managing your Node.js code.
 Command Line Interface (CLI): Familiarity with the command line (Terminal on
macOS/Linux or Command Prompt/Powershell on Windows) will help you execute
commands and manage Node.js.

Installing Node.js

Node.js can be installed on all major operating systems, including Windows, macOS, and Linux.

1. Download the Installer:


o Visit the official Node.js website at https://nodejs.org.
o Download the LTS (Long Term Support) version for stability and long-term
updates.
o You can also choose the Current version for the latest features, but LTS is
recommended for production environments.
2. Run the Installer:
o Once the installer is downloaded, run the .msi file.
o Follow the installation instructions. Ensure that the option to install npm (Node
Package Manager) is selected.
oThe installer will also add Node.js to your system's PATH, so you can run it from
the command line.
3. Verify the Installation:
o After installation, open the Command Prompt (or PowerShell) and run the
following commands to verify that Node.js and npm are installed successfully:

node -v
npm -v

o These commands will display the installed versions of Node.js and npm,
confirming the successful installation.

REPL Terminal
A REPL (Read-Eval-Print-Loop) terminal in Node.js is an interactive environment that allows
developers to run JavaScript code directly in the terminal. It provides a way to test snippets of
code, debug, and experiment with functions, objects, and expressions in real-time without
needing to create a file or execute a script.
Read: It reads the input from the user (JavaScript code).
Eval: It evaluates the input and executes the JavaScript code.
Print: It prints the result of the evaluation to the terminal.
Loop: It loops back to read the next input after showing the result.
To start the REPL terminal, simply run the command node in your terminal. The REPL
environment will open, and you can start typing JavaScript code directly.
$ node
> let x = 5
>x+2
7
You can exit the REPL by typing .exit or pressing Ctrl+C twice.
Instant feedback: Test small pieces of code quickly.
Debugging: Useful for testing functions, libraries, or debugging issues.
Learning tool: Ideal for beginners to experiment with JavaScript syntax and concepts.
Node.js REPL is a powerful tool for rapid development and exploration of JavaScript code.
Use Variables
You can make use variables to store values and print later like any conventional script. If var
keyword is not used then value is stored in the variable and printed. Whereas if var keyword is
used then value is stored but not printed. You can print variables usind console.log.
Multiline Expression
Node REPL supports multiline expression similar to JavaScript. Let's check the following do-
while
loop in action:
$ node
> var x = 0
undefined
> do {
... x++;
... console.log("x: " + x);
... } while ( x < 5 );
x: 1
x: 2
x: 3
x: 4
x: 5
undefined
>

REPL Commands
ctrl + c - terminate the current command.
ctrl + c twice - terminate the Node REPL.
ctrl + d - terminate the Node REPL.
Up/Down Keys - see command history and modify previous commands.
tab Keys - list of current commands.
.help - list of all commands.
.break - exit from multiline expression.
.clear - exit from multiline expression
.save filename - save current Node REPL session to a file.
.load filename - load file content in current Node REPL session.
WHAT IS NPM?
npm (Node Package Manager) is a popular package manager for JavaScript programming
developers. It was initially released in 2010, and is automatically installed by default whenever
you install Node.js on your system.
Node Package Manager npm provides following two main functionalities:

 Online repositories for node.js packages/modules which are searchable on


search.nodejs.org
 Command line utility to install Node.js packages, do version management and
dependency management of Node.js packages.
Installing Modules using npm
There is a simple syntax to install any Node.js module:
$ npm install <Module Name>
For example, following is the command to install a famous Node.js web framework module
called express:
$ npm install express
Now you can use this module in your js file as following:
var express = require('express');
Using package.json
package.json is present in the root directory of any Node application/module and is used to
define the properties of a package. Let's open package.json of express package present in
node_modules/express/

Attributes of Package.json

 name - name of the package


 version - version of the package
 description - description of the package
 homepage - homepage of the package
 author - author of the package
 contributors - name of the contributors to the package
 dependencies - list of dependencies. npm automatically installs all the dependencies
 mentioned here in the node_module folder of the package.
 repository - repository type and url of the package
 main - entry point of the package
 keywords - keywords
Callback Concept

Callback Concept: A Callback is a function that is called automatically when a particular task
is completed. The Callback function allows the program to run other code until a certain
task is not completed. The callback function is heavily used in nodeJS. The callback function
allows you to perform a large number of I/O operations that can be handled by your OS
without waiting for any I/O operation to finish. It makes nodeJS highly scalable.

For example: In Node.js, when a function starts reading a file, It’s obviously going to take
some time so without waiting for that function to complete, it returns control to the
execution environment immediately an executes the succeeding instruction. Once file I/O
gets completed, the callback function will be automatically called hence there will be no
waiting or blocking for file I/O.
Note: The callback function is being replaced by async/await these days.
Syntax: Let’s see the syntax of the callback function.
const fs = require("fs");
fs.readFile("file_path", "utf8", function (err, data) {
if (err) {
// Handle the error
} else {
// Process the file text given with data
}
});
Events
Each action on the computer is called an event. In nodeJS objects can fire events. According
to the official documentation of Node.js, it is an asynchronous event-driven JavaScript
runtime. Node.js has an event-driven architecture that can perform asynchronous tasks.
Node.js has an ‘events’ module that emits named events that can cause corresponding
functions or callbacks to be called. Functions(Callbacks) listen or subscribe to a particular
event to occur and when that event triggers, all the callbacks subscribed to that event are
fired one by one in order to which they were registered.
The EventEmmitter class: All objects that emit events are instances of the EventEmitter
class. The event can be emitted or listened to an event with the help of EventEmitter.
Syntax:
const EventEmitter=require('events');
var eventEmitter=new EventEmitter();

The following table lists all the important methods of the EventEmitter class:

Node.js – Packaging
A large-sized Node.js project usually has a number of dependencies and a number of source
files as well as other assets such as images, web pages, setting files etc. To distribute a
Node.js project and deploy it on any other environment becomes difficult, and hence it
needs to packaged so that it can be easily ported to other machine. There are a number of
packaging tools available on NPM repository.
 A package in Node.js contains all the files you need for a module.

 Modules are JavaScript libraries you can include in your project.

Download a Package

Downloading a package is very easy.

Open the command line interface and tell NPM to download the package you want.

I want to download a package called "upper-case":

Express Framework
Express is a minimal and flexible Node.js web application framework that provides a robust
set of features to develop web and mobile applications. It facilitates a rapid development of
Node based Web applications. Following are some of the core features of Express
framework:

 Allows to set up middlewares to respond to HTTP Requests.


 Defines a routing table which is used to perform different action based on HTTP
Method and URL.
 Allows to dynamically render HTML Pages based on passing arguments to templates.
Installing Express
Firstly, install the Express framework globally using npm so that it can be used to create
web
application using node terminal.
$ npm install express –save
Features of Express framework:

 It can be used to design single-page, multi-page and hybrid web applications.


 It allows to setup middlewares to respond to HTTP Requests.
 It defines a routing table which is used to perform different actions based on HTTP
method and URL.
 It allows to dynamically render HTML Pages based on passing
 arguments to templates.
State the differences between Node.js and Express.js
• Node.js is a platform for building the i/o applications which are server-side event-driven
and made using JavaScript.
• Express.js is a framework based on Node.js which is used for building web-application
using approaches and principles of Node.js eventdriven architecture.
Save the above code in a file named server.js and run it with the following command.
$ node server.js
You will see the following output:
Example app listening at http://0.0.0.0:8081
REST stands for REpresentational State Transfer. REST is web standards based architecture and
uses HTTP Protocol. It revolves around resource where every component is a resource and a
resource is accessed by a common interface using HTTP standard methods. REST was first
introduced by Roy Fielding in 2000.
A REST Server simply provides access to resources and REST client accesses and modifies the
resources using HTTP protocol. Here each resource is identified by URIs/ global IDs. REST
uses various representation to represent a resource like text, JSON, XML but JSON is the
most popular one
HTTP methods
Following four HTTP methods are commonly used in REST based architecture.

 GET - This is used to provide a read only access to a resource.


 PUT - This is used to create a new resource.
 DELETE - This is used to remove a resource.
 POST - This is used to update a existing resource or create a new resource.
RESTful Web Services
A web service is a collection of open protocols and standards used for exchanging data between
applications or systems. Software applications written in various programming languages and
running on various platforms can use web services to exchange data over computer networks
like the Internet in a manner similar to inter-process communication on a single computer.
List Users

Let's implement our first RESTful API listUsers using the following code in a server.js file:

Now try to access defined API using http://127.0.0.1:8081/listUsers on local machine. This should
produce following result: You can change given IP address when you will put the solution in production
environment.

MongoDB

Introduction: MongoDB is a popular, open-source NoSQL database system. Unlike traditional


relational databases that use tables and rows, MongoDB stores data in flexible, JSON-like
documents, making it ideal for handling large volumes of unstructured or semi-structured data.
It is a document-oriented database that allows scalability, flexibility, and easy querying.

1. Schema-less Database:
o MongoDB is schema-less, meaning each document in a collection can have a
different structure. This allows for greater flexibility when handling diverse data.
2. Document-Oriented Storage:
o Data in MongoDB is stored in BSON (Binary JSON) format. Each document is a set
of key-value pairs and can contain nested arrays or other documents.
3. Collections:
o Documents are stored in collections, which are analogous to tables in relational
databases. A collection can hold multiple documents.
4. Horizontal Scalability:
o MongoDB supports horizontal scaling through sharding. Data can be distributed
across multiple machines, improving performance and handling large-scale data
storage needs.
5. Indexing:
o MongoDB supports various types of indexes (e.g., single-field, compound,
geospatial, and text indexes), which help in improving query performance.

Node.js with MongoDB

Node.js is a popular JavaScript runtime that enables building scalable and efficient server-side
applications. MongoDB, a NoSQL database, works seamlessly with Node.js due to its JSON-like
document storage, making it an ideal choice for modern web applications. Using MongoDB with
Node.js allows you to create applications that can store, retrieve, and manipulate data
efficiently.

Here’s a basic overview of how to integrate MongoDB with a Node.js application:

Steps to Use MongoDB with Node.js:

1. Install MongoDB:

 MongoDB can be installed locally or used as a cloud service like MongoDB Atlas.
 MongoDB Atlas is a fully-managed cloud service for MongoDB, and it's free for small-scale
applications.

To install MongoDB locally, follow the instructions on the MongoDB website.

2. Install Dependencies:

You need to install the MongoDB Node.js driver or Mongoose (an Object Data Modeling (ODM)
library for MongoDB and Node.js).

 MongoDB Driver:

npm install mongodb


npm install mongoose

3. Basic Code Example Using MongoDB with Node.js (Native Driver)

Create a simple Node.js application that connects to MongoDB and performs CRUD operations.

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

const url = 'mongodb://localhost:27017';

const dbName = 'myDatabase';

async function main() {

const client = new MongoClient(url);

try {

// Connect to MongoDB

await client.connect();

console.log("Connected to MongoDB!");

const db = client.db(dbName);

const collection = db.collection('users');

// Insert a document

const user = { name: 'John Doe', age: 30 };

await collection.insertOne(user);

console.log("User inserted");

// Find a document

const foundUser = await collection.findOne({ name: 'John Doe' });

console.log("Found user:", foundUser);


// Update a document

await collection.updateOne({ name: 'John Doe' }, { $set: { age: 31 } });

console.log("User updated");

// Delete a document

await collection.deleteOne({ name: 'John Doe' });

console.log("User deleted");

} catch (err) {

console.error(err);

} finally {

await client.close();

main().catch(console.error);

4. Using Mongoose (Recommended for Ease of Use)

Mongoose is a higher-level abstraction over the MongoDB native driver. It provides a schema-
based solution to model the data and offers built-in validation, hooks, and other helpful
features.
1. Create Database

 In MongoDB, a database is created when you first insert data into a collection. You don't
explicitly create a database; it is automatically created when you perform an operation like
inserting a document.

Example (Using MongoDB shell or Node.js MongoDB driver):

use myDatabase; // Switch to the 'myDatabase' database (if it doesn't exist, MongoDB creates
it).

2. Create Collection

 A collection in MongoDB is equivalent to a table in relational databases. You can create a


collection explicitly or implicitly. MongoDB automatically creates a collection when you insert a
document into it.

Example (Using MongoDB shell):

db.createCollection('users'); // Explicitly creates a collection named 'users'

Example (Using Node.js):

db.collection('users').insertOne({ name: 'Alice', age: 30 });

MongoDB automatically creates the users collection when you insert data.

3. Insert

 Insert is used to add documents to a collection. MongoDB provides methods like insertOne() and
insertMany() to insert single or multiple documents at once.

db.users.insertOne({ name: 'John', age: 25 }); // Insert a single document

db.users.insertMany([{ name: 'Alice', age: 30 }, { name: 'Bob', age: 35 }]); // Insert multiple
documents

Example (Using Node.js):

const collection = db.collection('users');

collection.insertOne({ name: 'John', age: 25 });


4. Delete

 Delete is used to remove documents from a collection. MongoDB provides deleteOne(),


deleteMany(), and remove() (deprecated) for deleting documents.

Example (Using MongoDB shell):

db.users.deleteOne({ name: 'John' }); // Deletes the first document that matches the filter
db.users.deleteMany({ age: { $gt: 30 } }); // Deletes all documents where age is greater than 30

Example (Using Node.js):

const collection = db.collection('users');


collection.deleteOne({ name: 'John' }); // Delete one document
collection.deleteMany({ age: { $lt: 30 } }); // Delete multiple documents
5. Update

 Update is used to modify the existing documents in a collection. MongoDB offers updateOne(),
updateMany(), and findAndModify() (deprecated) for updating documents.

Example (Using MongoDB shell):

db.users.updateOne({ name: 'John' }, { $set: { age: 26 } }); // Update a single document


db.users.updateMany({ age: { $lt: 30 } }, { $set: { status: 'young' } }); // Update multiple documents

Example (Using Node.js):

const collection = db.collection('users');


collection.updateOne({ name: 'John' }, { $set: { age: 26 } });
collection.updateMany({ age: { $lt: 30 } }, { $set: { status: 'young' } });
6. Join

 MongoDB does not support traditional SQL joins. However, embedding documents or
referencing documents can achieve similar results. Additionally, MongoDB provides the $lookup
aggregation operator to join collections in the aggregation pipeline.

Example (Using MongoDB Aggregation with $lookup):

db.orders.aggregate([
{
$lookup: {
from: 'products',
localField: 'product_id',
foreignField: '_id',
as: 'productDetails'
}
}
]);
 This performs a left outer join between the orders collection and the products collection,
matching the product_id field from orders with the _id field from products.

7. Sort

 Sort is used to arrange the documents in a collection in ascending or descending order based on
a specified field.

Example (Using MongoDB shell):

db.users.find().sort({ age: 1 }); // Sort in ascending order by 'age'


db.users.find().sort({ age: -1 }); // Sort in descending order by 'age'

Example (Using Node.js):

const collection = db.collection('users');


collection.find().sort({ age: 1 }).toArray((err, docs) => {
console.log(docs);
});
8. Query

 Query in MongoDB is used to find documents that match specific conditions. MongoDB supports
a rich set of query operators like $gt, $lt, $eq, $in, etc.

Example (Using MongoDB shell):

db.users.find({ age: { $gt: 30 } }); // Find users older than 30


db.users.find({ name: 'John' }); // Find users with the name 'John'

Example (Using Node.js):

const collection = db.collection('users');


collection.find({ age: { $gt: 30 } }).toArray((err, docs) => {
console.log(docs);
});

You might also like