Unit4 Web Tech
Unit4 Web Tech
Types of EJB
EJB is an acronym for Enterprise Java Beans. It is a server-side software element. It
encapsulates the business logic of an application. It is a specification for developing a
distributed business application on the Java platform. There are three types of EJBs: Session
Bean, Entity Bean, and Message-Driven Bean. In this section,
Session Bean
The bean sprout business idea that can be systematically used by customer, remote, and web
service. When a client wants to use an application distributed on a server, then the client uses
session bean methods. This session bean provides services to customers, protecting them from
complex problems by performing business operations within the server.
To get to an application that is conveyed to the worker, the client summons the meeting bean's
strategies. The meeting bean performs work for its client, safeguarding it from intricacy by
executing business errands inside the worker. Remember that session beans are not persistence.
There are two types of session beans:
● Stateless Session Beans
● Stateful Session Beans
● Singleton Session Beans
Stateless Session Beans
A stateless session bean doesn't keep a conversational state with the customer or client. When
a client invokes the methods for a stateless bean, the bean's instance variable may contain a
state explicitly to that client however only for the span of the invocation.
At the point when the method has finished, the client explicit state should not be held. However,
the client may change the state of instance variable presented in pooled stateless beans, and
this state is held over to the following invocation of the pooled stateless bean.
Since they can maintain various customers, stateless session beans can offer better adaptability
for applications that require large numbers of clients. Ordinarily, an application requires fewer
stateless session beans than stateful session beans to support the same number of clients.
To improve execution, we may choose a stateless session bean in the event that it has any of
these characteristics
● The state of the bean has no information or data for a particular client.
● In a private method invocation, the bean performs a generic task for all clients.
● The bean implements a web service.
Stateful Session Beans
A stateful session bean is the same as an interactive session. The state of an object comprises
the values of its instance variables. In a stateful session bean, the instance variables denote the
state of a unique client/bean session. Since, the client interacts with its bean. The state is usually
called the conversational state. It maintains the state of a client across multiple requests. So, we
cannot implement it in the web services because it cannot be shared. When the client terminates
the session, it is no longer associated with the client.
The state is held for the span of the client/bean session. In case if the client eliminates the bean,
the session closes and the state is omitted. This transient nature of the state isn't an issue,
because the interaction between the client and the beans ends. So, it is not required to hold the
state.
Stateful session beans should be used, if any of the following conditions are valid:
● The bean's state denotes the alliance between the bean and a particular client.
● The bean needs to hold data about the customer across method invocations.
● The bean interferes between the customer and different segments of the application,
introducing an improved visible to the client.
● In the background, the bean deals with the workstream of a few enterprise beans.
Singleton Session Beans
A singleton session bean maintains one instance per application and the instance exists for the
lifecycle of the application. It offers the same functionality as the stateless session beans. But
the only difference is that there is only one singleton session bean per application while in the
stateless session bean a pool of beans is used.
From that pool, any of the session beans may respond to the client. We can implement it in the
web-service endpoints. It takes care of the state but does not hold the state if unexpected
crashes or shutdown occur. It can be used if we want to perform cleanup tasks on closing the
application or shut down as well. It is because it operates throughout the life cycle of the
application.
Singleton session beans are suitable for the following conditions:
● The state of the bean must be shared across the application.
● A single enterprise bean should be accessed by multiple threads concurrently.
● The application needs an enterprise bean to perform undertakings upon application
startup and shutdown.
● The bean implements a web service.
Entity Bean
An entity bean is an unpredictable business substance. It models a business substance or
models different activities inside a business interaction. It is used to encourage business
benefits that include data and calculations on that data. It can deal with various, needy, diligent
articles in playing out its essential assignments. A substance bean is a far-off object that
oversees steady information and performs complex business rationale. It can be extraordinarily
distinguished by an essential key.
It is a far-off object that oversees steady information, performs complex business rationale,
possibly utilizes a few ward Java protests, and can be remarkably distinguished by an essential
key. It ordinarily coarse-grained determined items since they use steady information put away
inside a few fine-grained relentless Java objects. Element beans are diligent on the grounds that
they do endure a worker crash or an organization's disappointment.
Every entity bean has a persistence identity that is associated with it. It means that it comprises
a unique identity that can be fetched if we have a primary key. The type for the unique key is
defined by the bean provider. A client can retrieve the entity bean if the primary has been
misplaced. If the bean is not available, the EJB container first, instantiates the bean and then re-
populates the data for the client.
The diligence for entity bean information is given both to saving state when the bean is
passivated and for improving the state when a failover has detected. It can endure in light of the
fact that the information is put away determinedly by the holder in some type of information
stockpiling framework, like a data set.
Entity beans persist business data by using the following two methods:
● Bean-Managed Persistence (BMP)
● Container-Managed Persistence (CMP)
Bean Managed Persistence
Bean-managed persistence is more complicated in comparison to container-managed
persistence. Because it allows us to write the persistence logic into the bean class, explicitly. In
order to write the persistence handling code into the bean class, we must know the type of
database that is being used and how fields of the bean class are mapped to the database.
Therefore, it provides more flexibility between the database and the bean instance.
Container-Managed Persistence
In container-managed persistence, the EJB container transparently and implicitly handles the
relationship between the bean and the database. Bean developers focus on the data and the
business process. The principal constraint is that the EJB compartment can most likely not
produce information base access articulations with the proficiency of a programmer.
Unlike BMP, CMP does not allow us to write database access calls in the methods of the entity
bean class. It is because the persistence is handled by the container at run-time. The following
two things are required to support the CMP:
● Mapping: It denotes that how to map an entity bean to a resource.
● Runtime Environment: A CMP runtime environment that uses the mapping information to
perform persistence operations on each bean.
Message-Driven Bean (MDB)
MDB is a Java Messaging Service (message listener). It consumes messages from a queue or
subscription of a topic. It provides an easy way to create or implement asynchronous
communication using a JMS message listener. An advantage of using MDB is that it allows us to
use the asynchronous nature of a JMS listener. We can implement message-driven beans with
Oracle JMS (Java Messaging Service).
There is an EJB container (contains MDBs pool) that handles the JMS queue and topic. Each
incoming message is handled by a bean that is invoked by the container. Note that no object
invokes an MDB directly. All invocation for MDB originates from the container. When the
container invokes the MDB, it can invoke other EJBs or Java objects to continue the request.
It is quite similar to stateless session bean. Because it does not save informal state, also used to
handle multiple incoming requests. EJB has the following benefits over the JMS are as follows:
● It creates a consumer for the listener. It means that the container creates QueueReceiver
or TopicSubscriber is created by the container.
● MDB is registered with the consumer. It means that at deployment time QueueReceiver,
TopicSubscriber, and its factory are registered by the container.
● The message ACK mode is specified.
The primary function of MDB is to read (receive) or write (send) incoming from a JMS destination
(i.e. queue or topic). While using MDB ensure that it is configured and installed properly. It
interacts with JMS and the JMS installed on the Oracle database. The database retains queue or
topic. The following figure depicts how MDB interacts with the JMS destination.
Node.js Introduction
Node.js is an open-source JavaScript server environment built on Chrome’s V8 engine. It is
open-source and free and runs on various platforms like Windows, Linux, Unix, MacOS, etc.
Node.js is an open-source, cross-platform JavaScript runtime environment that allows
developers to run JavaScript code on the server side. Created by Ryan Dahl in 2009, Node.js has
revolutionized server-side programming by offering an efficient, event-driven, and non-blocking
I/O model.
It’s a powerful tool used for various types of projects. Let’s explore some key aspects:
● JavaScript Runtime: Node.js runs on the V8 JavaScript engine, which is also the core
engine behind Google Chrome.
● Single Process Model: A Node.js application operates within a single process, avoiding
●
the need to create a new thread for every request.
● Asynchronous I/O: Node.js provides a set of asynchronous I/O primitives in its standard
library. These primitives prevent JavaScript code from blocking, making non-blocking
behavior the norm.
● Concurrency Handling: Node.js efficiently handles thousands of concurrent
connections using a single server. It avoids the complexities of managing thread
concurrency, which can lead to bugs.
● JavaScript Everywhere: Frontend developers familiar with JavaScript can seamlessly
transition to writing server-side code using Node.js.
● ECMAScript Standards: Node.js supports the latest ECMAScript standards. You can
choose the version you want to use, independent of users’ browser updates.
To get started and master the fundamentals, the Full Stack Development with Node JS course
offers a complete guide to creating server-side applications using Node.js.
Why Node.JS?
Node.js is used to build back-end services like APIs like Web App, Mobile App or Web Server. A
Web Server will open a file on the server and return the content to the client. It’s used in
production by large companies such as Paypal, Uber, Netflix, Walmart, and so on.
Reasons to Choose Node.js
● Easy to Get Started: Node.js is beginner-friendly and ideal for prototyping and agile
development.
● Scalability: It scales both horizontally and vertically.
● Real-Time Web Apps: Node.js excels in real-time synchronization.
● Fast Suite: It handles operations quickly (e.g., database access, network connections).
● Unified Language: JavaScript everywhere—frontend and backend.
● Rich Ecosystem: Node.js boasts a large open-source library and supports asynchronous,
non-blocking programming.
How Node.JS Works?
Node.js accepts the request from the clients and sends the response, while working with the
request node.js handles them with a single thread. To operate I/O operations or requests node.js
use the concept of threads. Thread is a sequence of instructions that the server needs to
perform. It runs parallel on the server to provide the information to multiple clients. Node.js is an
event loop single-threaded language. It can handle concurrent requests with a single thread
without blocking it for one request.
Advantages of Node.JS
● Easy Scalability: Easily scalable the application in both horizontal and vertical directions.
● Real-time web apps: Node.js is much more preferable because of faster synchronization.
Also, the event loop avoids HTTP overloaded for Node.js development.
● Fast Suite: NodeJS acts like a fast suite and all the operations can be done quickly like
reading or writing in the database, network connection, or file system
● Easy to learn and code: NodeJS is easy to learn and code because it uses JavaScript.
● Advantage of Caching: It provides the caching of a single module. Whenever there is any
request for the first module, it gets cached in the application memory, so you don’t need
to re-execute the code.
How Node.JS Works?
Node.js accepts the request from the clients and sends the response, while working with the
request node.js handles them with a single thread. To operate I/O operations or requests node.js
use the concept of threads. Thread is a sequence of instructions that the server needs to
perform. It runs parallel on the server to provide the information to multiple clients. Node.js is an
event loop single-threaded language. It can handle concurrent requests with a single thread
without blocking it for one request.
Advantages of Node.JS
● Easy Scalability: Easily scalable the application in both horizontal and vertical directions.
● Real-time web apps: Node.js is much more preferable because of faster synchronization.
Also, the event loop avoids HTTP overloaded for Node.js development.
● Fast Suite: NodeJS acts like a fast suite and all the operations can be done quickly like
reading or writing in the database, network connection, or file system
● Easy to learn and code: NodeJS is easy to learn and code because it uses JavaScript.
● Advantage of Caching: It provides the caching of a single module. Whenever there is any
request for the first module, it gets cached in the application memory, so you don’t need
to re-execute the code.
What is Node.JS file?
Node.js files contain tasks that handle file operations like creating, reading, deleting, etc.,
Node.js provides an inbuilt module called FS (File System).
Application of Node.JS
Node.js is suitable for various applications, including:
● Real-time chats
● Complex single-page applications
● Real-time collaboration tools
● Streaming apps
● JSON APIs
Common Use Cases of Node.JS
Node.js is versatile and finds applications in various domains:
1. Web Servers: Node.js excels at building lightweight and efficient web servers. Its non-
blocking I/O model makes it ideal for handling concurrent connections.
2. APIs and Microservices: Many companies use Node.js to create RESTful APIs and
microservices. Express.js simplifies API development.
3. Real-Time Applications: Node.js shines in real-time scenarios like chat applications, live
notifications, and collaborative tools. Socket.io facilitates real-time communication.
4. Single-Page Applications (SPAs): SPAs benefit from Node.js for server-side rendering
(SSR) and handling API requests.
5. Streaming Services: Node.js is well-suited for streaming data, whether it’s video, audio,
or real-time analytics.
Node.js Environment Setup
This Node.js tutorial consists of a number of ready-to-run examples, so that the learn can
understand the Node.js concepts by running the code. To be able to execute the example code,
you can use our online Node.js environment, or install Node.js environment in your local machine.
Local Environment Setup
If you are still willing to set up your environment for Node.js, this section will guide you. Node.js
can be installed on different OS platforms such as Windows, Linux, Mac OS X, etc. You need the
following tools on your computer −
● The Node.js binary installer
● Node Package Manager (NPM)
● IDE or Text Editor
Binaries for various OS platforms are available on the downloads page of the official website of
Node.js. Visit https://nodejs.org/en/downloadto get the list.
This page shows two sets of binaries for different OS platforms, one for the current or latest
version, and the other a version with LTS (Long Term Support), that is recommended for a normal
user. 32 bit and 64 bit installers as well as ZIP archives for Windows, macOS installer as well as
tar archives and binaries for Linux OS on x64 and ARM architecture are available.
Installation on Windows
Assuming that you are working with Windows 10/Windows 11 powered computer, download the
64-bit installer for Windows: https://nodejs.org/dist/v20.9.0/node-v20.9.0-x64.msi, and start the
installation b double-clicking the downloaded file.
The installation takes you through a few steps of the installation wizard. It also adds the
installation directory of Node.js executable to the system path.
To verify if Node.js has been successfully installed, open the command prompt and type node -v.
If Node.js is installed successfully then it will display the version of the Node.js installed on your
machine, as shown below.
Node.js REPL
The term REPL stands for Read Eval Print and Loop. It specifies a computer environment like a
window console or a Unix/Linux shell where you can enter the commands and the system
responds with an output in an interactive mode.
REPL Environment
The Node.js or node come bundled with REPL environment. Each part of the REPL environment
has a specific work.
Read: It reads user's input; parse the input into JavaScript data-structure and stores in memory.
Eval: It takes and evaluates the data structure.
Print: It prints the result.
Loop: It loops the above command until user press ctrl-c twice.
How to start REPL
You can start REPL by simply running "node" on the command prompt. See this:
You can execute various mathematical operations on REPL Node.js command prompt:
Node.js Simple expressions
After starting REPL node command prompt put any mathematical expression:
● Example: >10+20-5
● 25
Using variable
Variables are used to store values and print later. If you don't use var keyword 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 using console.log().
Node.js Multiline expressions
Node REPL supports multiline expressions like JavaScript. See the following do-while loop
example:
● var x = 0
● undefined
● > do {
● ... x++;
● ... console.log("x: " + x);
● ... } while ( x < 10 );
You can use npm ls command to list down all the locally installed modules.
Open the Node.js command prompt and execute "npm ls":
Globally installed packages/dependencies are stored in system directory. Let's install express
module using global installation. Although it will also produce the same result but modules will be
installed globally.
Open Node.js command prompt and execute the following code:
● npm install express -g
Here first line tells about the module version and its location where it is getting installed.
Uninstalling a Module
To uninstall a Node.js module, use the following command:
● npm uninstall express
The Node.js module is uninstalled. You can verify by using the following command:
● npm ls
setTimeout(function () {
console.log('This prints after 1000 ms');
}, 1000);
console.log("Hello World");
Output
Hello World
This prints after 1000 ms
Node.js Events
Node.js is built on an event-driven architecture that allows you to build highly scalable
applications. Understanding the event-driven nature of Node.js and how to work with events is
important for building efficient and responsive applications.
What Are Events in Node.js?
In Node.js, an event is an action or occurrence that the program can detect and handle. The
event-driven architecture allows asynchronous programming, and your application becomes able
to perform non-blocking operations. This means that while waiting for an operation to complete
(like reading a file or making a network request), the application can continue processing other
tasks.
EventEmitter Class
At the core of the Node.js event system is the EventEmitter class. This class allows objects to
emit named events that can be listened to by other parts of your application. It is included in the
built-in events module.
Key Features of EventEmitter:
● Event Registration: You can register listeners for specific events using the on() method.
● Event Emission: Use the emit() method to trigger an event and call all registered listeners
for that event.
● Asynchronous Execution: Listeners can execute asynchronously, allowing other
operations to continue while waiting for events.
Syntax:
const EventEmitter=require('events');
var eventEmitter=new EventEmitter();
Working with Events in Node.js
Step 1: Importing the Events Module
To start using events in your application, you need to import the events module
and create an instance of the EventEmitter class.
const EventEmitter = require('events');
const myEmitter = new EventEmitter();
Step 2: Registering Event Listeners
You can register listeners for specific events using the on() method. The first
argument is the event name, and the second argument is the callback function to
be executed when the event is emitted.
myEmitter.on('event', () => {
console.log('An event occurred!');
});
Step 3: Emitting Events
To trigger an event, use the emit() method with the event name as the first
argument.
myEmitter.emit('event'); // Output: An event occurred!
Listening events
Before emitting any event, it must register functions(callbacks) to listen to the
events.
Syntax:
eventEmitter.addListener(event, listener)
eventEmitter.on(event, listener)
eventEmitter.once(event, listener)
Removing Listener
The eventEmitter.removeListener() takes two argument event and listener, and
removes that listener from the listeners array that is subscribed to that event.
While eventEmitter.removeAllListeners() removes all the listener from the array
which are subscribed to the mentioned event.
Syntax:
eventEmitter.removeListener(event, listener)
eventEmitter.removeAllListeners([event])
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. This chapter discusses nexe packaging tool, and also takes
overview of some other packaging libraries.
Nexe
To demonstrate how the Nexe utility works, we shall an ExpressJs app with the following script −
Index.js
var express = require('express');
var app = express();
var path = require('path');
var bodyParser = require('body-parser');
// Create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })
app.use(express.static('public'));
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname,"index.html"));
})
app.get('/process_get', function (req, res) {
// Prepare output in JSON format
response = {
first_name:req.query.first_name,
last_name:req.query.last_name
};
console.log(response);
res.end(JSON.stringify(response));
})
app.post("/process_post", )
var server = app.listen(5000, function () {
console.log("Express App running at http://127.0.0.1:5000/");
})
The ‘/’ route renders a HTML form from the following script −
Index.html
<html>
<body>
<form action = "/process_POST" method = "POST">
First Name: <input type = "text" name = "first_name"> <br>
Last Name: <input type = "text" name = "last_name"> <br>
<input type = "submit" value = "Submit">
</form>
</body>
</html>
The Node.js server displays the following form −
Features of Nexe
● Self contained applications
● Ability to run multiple applications with different node.js runtimes.
● Distribute binaries without needing node / npm.
● Start and deploy faster.
● Flexible build pipeline
● Cross platform builds
Install Nexe on Windows
Perform global installation of Nexe as follows −
npm install nexe -g
You also need Netwide Assembler (NASM) tool. Download and install the same from
www.nasm.us
The nexe utility requires Python installed on the system. Ensure that Python is one of the
versions 3.11 to 3.7.
Assuming that you are using nexe for 64-bit Windows OS, you also need to install The "Desktop
development with C++" workload from Visual Studio 2022. It can be installed from aka.ms.
(For other OS platforms, follow the instructions on github.com/nodejs
Once all the prerequisites are installed, run the following command in the CMD terminal −
D:\expressApp>nexe index.js --build windows-x64-20.9.0 –verbose
The compilation may take a while, but in the end, it will create expressApp.exe in the application
folder.
D:\expressApp
│ expressApp.exe
│ index.html
│ index.js
│ package-lock.json
│ package.json
│ users.json
│
├───node_modules
│ │ .package-lock.json
│ ├───body-parser
│ │ │ HISTORY.md
│ │ │ index.js
│ │ │ LICENSE
│ │ │ package.json
│ │ │ README.md
│ │ │ SECURITY.md
│ │ │ ...
│ │ │ ...
│ │ │ ...
│ ├───express
│ │ │ History.md
│ │ │ index.js
│ │ │ LICENSE
│ │ │ package.json
│ │ │ Readme.md
│ │ │ ...
│ │ │ ...
│ │ │ ...
└───public
└───images
logo.png
Run it from the command line, and the Node.js server starts.
D:\expressApp>expressapp
Express App running at http://127.0.0.1:5000/
pkg tool
The pkg tool is a command-line interface that enables the developer to create executables from
Node.JS projects; allowing you to run the app even on environments that do not have Node.JS
installed on them.
To install pkg, use the command −
npm install -g pkg
Then use pkg to build the executable
pkg myapp.js
Running the above command will generate three programmes; namely an executable for
Windows, macOS, and Linux. More details can be found at www.npmjs.com.
JXCore
JXcore, which is an open source project, introduces a unique feature for packaging and
encryption of source files and other assets into JX packages.
Download and install the JXcore package from https://github.com/jxcore, as per your operating
system and machine architecture.
To package the above project, you simply need to go inside this directory and issue the following
jx command. Assuming index.js is the entry file for your Node.js project −
jx package index.js index
the above command will pack everything and will create the following two files −
index.jxp − This is an intermediate file which contains the complete project detail needed to
compile the project.
index.jx − This is the binary file having the complete package that is ready to be shipped to your
client or to your production environment.
Consider your original Node.js project was running as follows −
node index.js command_line_arguments
After compiling your package using JXcore, it can be started as follows −
jx index.jx command_line_arguments
In HTTP there are five methods that are commonly used in a REST-based Architecture i.e., POST,
GET, PUT, PATCH, and DELETE. These correspond to create, read, update, and delete (or CRUD)
operations respectively. There are other methods which are less frequently used like OPTIONS
and HEAD.
● GET: The HTTP GET method is used to read (or retrieve) a representation of a resource. In
the safe path, GET returns a representation in XML or JSON and an HTTP response code
of 200 (OK). In an error case, it most often returns a 404 (NOT FOUND) or 400 (BAD
REQUEST).
● POST: The POST verb is most often utilized to create new resources. In particular, it’s
used to create subordinate resources. That is, subordinate to some other (e.g. parent)
resource. On successful creation, return HTTP status 201, returning a Location header
with a link to the newly-created resource with the 201 HTTP status.
NOTE: POST is neither safe nor idempotent.
● PUT: It is used for updating the capabilities. However, PUT can also be used to create a
resource in the case where the resource ID is chosen by the client instead of by the server.
In other words, if the PUT is to a URI that contains the value of a non-existent resource ID.
On successful update, return 200 (or 204 if not returning any content in the body) from a
PUT. If using PUT for create, return HTTP status 201 on successful creation. PUT is not
safe operation but it’s idempotent.
● PATCH: It is used to modify capabilities. The PATCH request only needs to contain the
changes to the resource, not the complete resource. This resembles PUT, but the body
contains a set of instructions describing how a resource currently residing on the server
should be modified to produce a new version. This means that the PATCH body should not
just be a modified part of the resource, but in some kind of patch language like JSON
Patch or XML Patch. PATCH is neither safe nor idempotent.
● DELETE: It is used to delete a resource identified by a URI. On successful deletion, return
HTTP status 200 (OK) along with a response body.
MongoDB - Create Database
The use Command
MongoDB use DATABASE_NAME is used to create database. The command will create a new
database if it doesn't exist, otherwise it will return the existing database.
Syntax
Basic syntax of use DATABASE statement is as follows −
use DATABASE_NAME
Example
If you want to use a database with name <mydb>, then use DATABASE statement would be as
follows −
>use mydb
switched to db mydb
To check your currently selected database, use the command db
>db
mydb
If you want to check your databases list, use the command show dbs.
>show dbs
local 0.78125GB
test 0.23012GB
Your created database (mydb) is not present in list. To display database, you need to insert at
least one document into it.
>db.movie.insert({"name":"tutorials point"})
>show dbs
local 0.78125GB
mydb 0.23012GB
test 0.23012GB
In MongoDB default database is test. If you didn't create any database, then collections will be
stored in test database.
The dropDatabase() Method
MongoDB db.dropDatabase() command is used to drop a existing database.
Syntax
Basic syntax of dropDatabase() command is as follows −
db.dropDatabase()
This will delete the selected database. If you have not selected any database, then it will delete
default 'test' database.
Example
First, check the list of available databases by using the command, show dbs.
>show dbs
local 0.78125GB
mydb 0.23012GB
test 0.23012GB
>
If you want to delete new database <mydb>, then dropDatabase() command would be as
follows −
>use mydb
switched to db mydb
>db.dropDatabase()
>{ "dropped" : "mydb", "ok" : 1 }
>
Now check list of databases.
>show dbs
local 0.78125GB
test 0.23012GB
>
> db.empDetails.insertOne(
{
First_Name: "Radhika",
Last_Name: "Sharma",
Date_Of_Birth: "1995-09-26",
e_mail: "[email protected]",
phone: "9848022338"
})
{
"acknowledged" : true,
"insertedId" : ObjectId("5dd62b4070fb13eec3963bea")
}
>
$aggregate() function
This function Performs a left outer join to another collection in the same database to filter in
documents from the "joined" collection for processing.
$lookup: Performs a left outer join to a collection in the same database to filter in documents
from the "joined" collection for processing. The $lookup stage adds a new array field to each
input document. The new array field contains the matching documents from the "joined"
collection.
To perform an equality match between a field from the input documents with a field from the
documents of the "joined" collection, the $lookup stage has this syntax −
{
$lookup:
{
from: <collection to join>,
localField: <field from the input documents>,
foreignField: <field from the documents of the "from" collection>,
as: <output array field>
}
}
The parameters in $lookup stage are as follows −
Node.js MongoDB Sorting
In MongoDB, the sort() method is used for sorting the results in ascending or descending order.
The sort() method uses a parameter to define the object sorting order.
● Node sortasc.js
Sort in Descending Order
Example
Sort the records in descending order according to name:
Create a js file named "sortdsc.js", having the following code:
● Node sortdsc.js