Unit 4 - Part 1 Notes
Unit 4 - Part 1 Notes
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.
1
// Importing the http module
2
const http = require('http');
3
4
// Creating a server
5
const server = http.createServer((req, res) => {
6
// Setting the content type to HTML
7
res.writeHead(200, {
8
'Content-Type': 'text/html'
9
});
10
11
// Sending the HTML response
12
res.end('<h1>Hello GFG</h1>');
13
});
14
15
// Listening on port 3000
16
const PORT = 3000;
17
server.listen(PORT, () => {
18
console.log(`Server running at http://localhost:${PORT}/`);
19
});
Output:
Example of Node.js Server Output
Code Explaination:
We use the HTTP module to create an HTTP server.
The server listens on the specified port and hostname.
When a new request arrives, the callback function handles it by setting
the response status, headers, and content.
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.
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 Ecosystem
Node.js has a vibrant ecosystem with a plethora of libraries, frameworks,
and tools. Here are some key components:
1. npm (Node Package Manager): npm is the default package manager
for Node.js. It allows developers to install, manage, and share reusable
code packages (called modules). You can find thousands of open-
source packages on the npm registry.
2. Express.js: Express is a popular web application framework for
Node.js. It simplifies routing, middleware handling, and
request/response management. Many developers choose Express for
building APIs, web servers, and single-page applications.
3. Socket.io: For real-time communication, Socket.io is a go-to library. It
enables bidirectional communication between the server and clients
using WebSockets or fallback mechanisms.
4. Mongoose: If you’re working with MongoDB (a NoSQL database),
Mongoose provides an elegant way to model your data and interact
with the database. It offers schema validation, middleware, and query
building.
NodeJS NPM
NPM (Node Package Manager) is a package manager
for Node.js modules. It helps developers manage project dependencies,
scripts, and third-party libraries. By installing Node.js on your system,
NPM is automatically installed, and ready to use.
It is primarily used to manage packages or modules—these are pre-
built pieces of code that extend the functionality of your Node.js
application.
The NPM registry hosts millions of free packages that you can
download and use in your project.
NPM is installed automatically when you install Node.js, so you don’t
need to set it up manually.
To master NPM and streamline your full-stack development workflow,
the Full Stack Development with Node JS course offers detailed
lessons on managing packages, scripts, and dependencies for full-stack
applications
How to Use NPM with Node.js?
To start using NPM in your project, follow these simple steps
Step 1: Install Node.js and NPM
First, you need to install Node.js. NPM is bundled with the Node.js
installation. You can follow our article to Install the Node and NPM- How
to install Node on your system
Step 2: Verify the Installation
After installation, verify Node.js and NPM are installed by running the
following commands in your terminal:
node -v
npm -v
These commands will show the installed versions of Node.js and NPM.
1
//app.js
2
3
const express = require('express');//import the required package
4
const app = express();
5
6
app.get('/', (req, res) => {
7
res.send('Hello, World!');
8
});
9
10
app.listen(3000, () => {
11
console.log('Server running at http://localhost:3000');
12
});
express() creates an instance of the Express app.
app.get() defines a route handler for HTTP GET requests to the root (/)
URL.
res.send() sends the response “Hello, World!” to the client.
app.listen(3000) starts the server on port 3000, and console.log()
outputs the server URL.
Now run the application with
node app.js
Visit http://localhost:3000 in your browser, and you should see the
message: Hello, World!
Managing Project Dependencies
1. Installing All Dependencies
In a Node.js project, dependencies are stored in a package.json file. To
install all dependencies listed in the file, run:
npm install
This will download all required packages and place them in the
node_modules folder.
2. Installing a Specific Package
To install a specific package, use:
npm install <package-name>
You can also install a package as a development dependency using:
npm install <package-name> --save-dev
Development dependencies are packages needed only during
development, such as testing libraries.
To install a package and simultaneously save it in package.json file (in
case using Node.js), add –save flag. The –save flag is default in npm
install command so it is equal to npm install package_name command.
Example:
npm install express --save
Usage of Flags:
–save: flag one can control where the packages are to be installed.
–save-prod : Using this packages will appear in Dependencies which
is also by default.
–save-dev : Using this packages will get appear in devDependencies
and will only be used in the development mode.
Note: If there is a package.json file with all the packages mentioned as
dependencies already, just type npm install in terminal
3. Updating Packages
You can easily update packages in your project using the following
command
npm update
This will update all packages to their latest compatible versions based on
the version constraints in the package.json file.
To update a specific package, run
npm update <package-name>
4. Uninstalling Packages
To uninstall packages using npm, follow the below syntax:
npm uninstall <package-name>
For uninstall Global Packages
npm uninstall package_name -g
Popular NPM Packages
NPM has a massive library of packages. Here are a few popular packages
that can enhance your Node.js applications:
Express: A fast, minimal web framework for building APIs and web
applications.
Mongoose: A MongoDB object modeling tool for Node.js.
Lodash: A utility library delivering consistency, customization, and
performance.
Axios: A promise-based HTTP client for making HTTP requests.
React: A popular front-end library used to build user interfaces.
Versioning in NPM
NPM allows you to manage package versions. This is important when you
want to ensure that a specific version of a library is used across all
environments.
For example
npm install [email protected]
This will install version 4.17.1 of Express, regardless of the latest version.
Using Semantic Versioning to manage packages
RESTful APIs are a popular way of creating web applications that exchange
data over the internet in a standardized manner. These APIs follow specific
principles such as using resource-based URLs and HTTP methods to
perform various operations like creating, reading, updating, and deleting
data. ExpressJS is a powerful framework that allows developers to easily
create routes, handle requests, and send responses, making it a versatile
choice for building APIs that are robust and scalable.
Understanding the concept of RESTful APIs in
Express JS:
REST Architecture: REST, which stands for Representational State
Transfer, is an architectural style for designing networked applications.
Resource-Based: RESTful APIs in ExpressJS are designed around
resources, which are identified by unique URLs. These resources
represent the entities (e.g., users, products, articles) that the API
manipulates.
HTTP Methods: RESTful APIs use standard HTTP methods to
perform CRUD (Create, Read, Update, Delete) operations on
resources:
o GET: Retrieves data from a resource.
o POST: Creates a new resource.
o PUT: Updates an existing resource.
o DELETE: Deletes a resource.
Statelessness: RESTful APIs are stateless, meaning that each
request from a client contains all the information needed to process the
request. Servers do not maintain a session state between requests.
Uniform Interface: RESTful APIs have a uniform interface, which
simplifies communication between clients and servers. This interface
typically involves the use of standard HTTP methods, resource
identifiers (URLs), and representations (e.g., JSON, XML).
ExpressJS and Routing: In ExpressJS, you define routes to handle
incoming requests for specific resources and HTTP methods. Each
route specifies a callback function to process the request and send an
appropriate response.
Middleware Integration: ExpressJS middleware can be used to
handle tasks such as request validation, authentication, and response
formatting, enhancing the functionality and security of RESTful APIs.
Response Codes: RESTful APIs use standard HTTP status codes to
indicate the success or failure of a request. Common status codes
include 200 (OK), 201 (Created), 400 (Bad Request), 404 (Not
Found), and 500 (Internal Server Error).
Example: Below are the example of RESTful APIs in ExpressJS.
Install the necessary package in your application using the following
command.
npm install express
Example: Below is the basic example of the RESTful API in ExpressJS.
JavaScript
1
// server.js
2
const express = require('express');
3
const app = express();
4
const PORT = 3000;
5
6
// To define the sample data
7
let books = [
8
{
9
id: 1,
10
title: 'The Great Gatsby',
11
author: 'F. Scott Fitzgerald'
12
},
13
{
14
id: 2,
15
title: 'To Kill a Mockingbird',
16
author: 'Harper Lee'
17
},
18
];
19
20
// Define routes for handling GET requests
21
app.get('/api/books',
22
(req, res) => {
23
res.json(books);
24
});
25
26
app.get('/api/books/:id',
27
(req, res) => {
28
const id =
29
parseInt(req.params.id);
30
const book =
31
books.find(book => book.id === id);
32
if (book) {
33
res.json(book);
34
} else {
35
res.status(404)
36
.json({ message: 'Book not found' });
37
}
38
});
39
40
app.listen(PORT,
41
() => {
42
console.log(`Server is running on port ${PORT}`);
43
});
Start your application using the following command.
node server.js
Node.js - Express Framework
Express.js is a minimal and flexible web application framework that provides
a robust set of features to develop Node.js based web and mobile
applications. Express.js is one of the most popular web frameworks in the
Node.js ecosystem. Express.js provides all the features of a modern web
framework, such as templating, static file handling, connectivity with SQL
and NoSQL databases.
Node.js has a built-in web server. The createServer() method in its http
module launches an asynchronous http server. It is possible to develop a
web application with core Node.js features. However, all the low level
manipulations of HTTP request and responses have to be tediously handled.
The web application frameworks take care of these common tasks, allowing
the developer to concentrate on the business logic of the application. A web
framework such as Express.js is a set of utilities that facilitates rapid, robust
and scalable web applications.
Save the above code as index.js and run it from the command-line.
D:\expressApp> node index.js
Express App running at http://127.0.0.1:5000/
Explore our latest online courses and learn new skills at your own pace. Enroll
and become a certified expert to boost your career.
Application object
An object of the top level express class denotes the application object. It is
instantiated by the following statement −
The app.listen() method creates the Node.js web server at the specified host
and port. It encapsulates the createServer() method in http module of
Node.js API.
app.listen(port, callback);
Basic Routing
The app object handles HTTP requests GET, POST, PUT and DELETE with
app.get(), app.post(), app.put() and app.delete() method respectively. The
HTTP request and HTTP response objects are provided as arguments to these
methods by the NodeJS server. The first parameter to these methods is a
string that represents the endpoint of the URL. These methods are
asynchronous, and invoke a callback by passing the request and response
objects.
GET method
In the above example, we have provided a method that handles the GET
request when the client visits '/' endpoint.
You can print request and response objects which provide a lot of information
related to HTTP request and response including cookies, sessions, URL, etc.
The response object also has a sendFile() method that sends the contents of
a given file as the response.
res.sendFile(path)
Save the following HTML script as index.html in the root folder of the express
app.
<html>
<body>
<h2 style="text-align: center;">Hello World</h2>
</body>
</html>
Run the above program and visit http://localhost:5000/, the browser shows
Hello World message as below:
Let us use sendFile() method to display a HTML form in the index.html file.
<html>
<body>
</body>
</html>
The above form submits the data to /process_get endpoint, with GET
method. Hence we need to provide a app.get() method that gets called when
the form is submitted.
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));
})
The form data is included in the request object. This method retrieves the
data from request.query array, and sends it as a response to the client.
app.use(express.static('public'));
Visit http://localhost:5000/.
Now you can enter the First and Last Name and then click submit button to
see the result and it should return the following result −
{"first_name":"John","last_name":"Paul"}
POST method
The HTML form is normally used to submit the data to the server, with its
method parameter set to POST, especially when some binary data such as
images is to be submitted. So, let us change the method parameter in
index.html to POST, and action parameter to "process_POST".
<html>
<body>
</body>
</html>
To handle the POST data, we need to install the body-parser package from
npm. Use the following command.
This is a node.js middleware for handling JSON, Raw, Text and URL encoded
form data.
This package is included in the JavaScript code with the following require
statement.
var bodyParser = require('body-parser');
app.use(express.static('public'));
Now you can enter the First and Last Name and then click the submit button
to see the following result −
{"first_name":"John","last_name":"Paul"}
You simply need to pass the name of the directory where you keep your
static assets, to the express.static middleware to start serving the files
directly. For example, if you keep your images, CSS, and JavaScript files in a
directory named public, you can do this −
Javascript
const fs = require("fs");
console.log(filedata.toString());
Now run the main.js to see the result with the following command:
node main.js
Explanation: In this example, we have an fs module of nodeJS that
provides the functionality of File I/O operations. With the help of the
readFileSync() function, we are able to use the Synchronous approach
here, which is also called the blocking function as it waits for each
instruction to be complete first before going to the next one. Hence in this
example, the function blocks the program until it reads the file and then
went ahead with the end of the program.
Output:
GFG
const fs = require("fs");
console.log(data.toString());
});
Now run the main.js to see the result with the following command:
node main.js
Explanation: With the help of the readFile() function, we are able to use
the Asynchronous approach here, which is also called a non-blocking
function as it never waits for each instruction to complete, rather it
executes all operations in the first go itself. Hence in this example, the
function runs in the background, and the control is returned to the next
instruction. When the background task is completed callback function is
called.
Output:
GFG
console.log('Learn nodejs!');
eventEmitter.on('event1', EventHandler);
eventEmitter.emit('event1');
Now run the main.js to see the result with the following command:
node main.js
Output:
// Importing events
const EventEmitter = require('events');
// Register to newListener
});
// Register to removeListener
});
};
};
eventEmitter.on('myEvent', fun1);
eventEmitter.on('myEvent', fun2);
// Removing listener
eventEmitter.off('myEvent', fun1);
// Triggering myEvent
Now run the main.js to see the result with the following command:
node main.js
Output:
Javascript
const fs = require("fs");
console.log(filedata.toString());
Now run the main.js to see the result with the following command:
node main.js
Explanation: In this example, we have an fs module of nodeJS that
provides the functionality of File I/O operations. With the help of the
readFileSync() function, we are able to use the Synchronous approach
here, which is also called the blocking function as it waits for each
instruction to be complete first before going to the next one. Hence in this
example, the function blocks the program until it reads the file and then
went ahead with the end of the program.
Output:
GFG
const fs = require("fs");
console.log(data.toString());
});
Now run the main.js to see the result with the following command:
node main.js
Explanation: With the help of the readFile() function, we are able to use
the Asynchronous approach here, which is also called a non-blocking
function as it never waits for each instruction to complete, rather it
executes all operations in the first go itself. Hence in this example, the
function runs in the background, and the control is returned to the next
instruction. When the background task is completed callback function is
called.
Output:
GFG
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:
console.log('Learn nodejs!');
eventEmitter.on('event1', EventHandler);
eventEmitter.emit('event1');
Now run the main.js to see the result with the following command:
node main.js
Output:
// Importing events
// Register to newListener
});
// Register to removeListener
});
};
};
// Listening to myEvent with fun1 and fun2
eventEmitter.on('myEvent', fun1);
eventEmitter.on('myEvent', fun2);
// Removing listener
eventEmitter.off('myEvent', fun1);
// Triggering myEvent
Now run the main.js to see the result with the following command:
node main.js
Output:
What is MongoDB
MongoDB is an open-source document database that provides high performance, high
availability, and automatic scaling.
In simple words, you can say that - Mongo DB is a document-oriented database. It is an
open source product, developed and supported by a company named 10gen.
MongoDB is available under General Public license for free, and it is also available under
Commercial license from the manufacturer.
MongoDB was designed to work with commodity servers. Now it is used by the company
of all sizes, across all industry.
History of MongoDB
The initial development of MongoDB began in 2007 when the company was building a
platform as a service similar to window azure.
The first ready production of MongoDB has been considered from version 1.4 which was
released in March 2010.
MongoDB2.4.9 was the latest and stable version which was released on January 10, 2014.
All the modern applications require big data, fast features development, flexible
deployment, and the older database systems not competent enough, so the MongoDB
was needed.
o Scalability
o Performance
o High Availability
o Scaling from single server deployments to large, complex multi-site
architectures.
o Key points of MongoDB
o Develop Faster
o Deploy Easier
o Scale Bigger
First of all, we should know what is document oriented database?
1. FirstName = "John",
2. Address = "Detroit",
3. Spouse = [{Name: "Angela"}].
4. FirstName ="John",
5. Address = "Wick"
There are two different documents (separated by ".").
Mongo DB falls into a class of databases that calls Document Oriented Databases. There
is also a broad category of database known as No SQL Databases.
Features of MongoDB
These are some important features of MongoDB:
In MongoDB, you can search by field, range query and it also supports regular expression
searches.
2. Indexing
3. Replication
A master can perform Reads and Writes and a Slave copies data from the master and
can only be used for reads or back up (not writes)
4. Duplication of data
MongoDB can run over multiple servers. The data is duplicated to keep the system up and
also keep its running condition in case of hardware failure.
5. Load balancing
10. Stores files of any size easily without complicating your stack.
$eq
The $eq specifies the equality condition. It matches documents where the value of a field
equals the specified value.
Syntax:
$gt
The $gt chooses a document where the value of the field is greater than the specified
value.
Syntax:
$gte
The $gte choose the documents where the field value is greater than or equal to a
specified value.
Syntax:
$in
The $in operator choose the documents where the value of a field equals any value in the
specified array.
Syntax:
$lt
The $lt operator chooses the documents where the value of the field is less than the
specified value.
Syntax:
$lte
The $lte operator chooses the documents where the field value is less than or equal to a
specified value.
Syntax:
$ne
The $ne operator chooses the documents where the field value is not equal to the
specified value.
Syntax:
$nin
The $nin operator chooses the documents where the field value is not in the specified
array or does not exist.
Syntax:
$and
The $and operator works as a logical AND operation on an array. The array should be of
one or more expressions and chooses the documents that satisfy all the expressions in
the array.
Syntax:
$not
The $not operator works as a logical NOT on the specified expression and chooses the
documents that are not related to the expression.
Syntax:
$nor
The $nor operator works as logical NOR on an array of one or more query expression and
chooses the documents that fail all the query expression in the array.
Syntax:
$or
It works as a logical OR operation on an array of two or more expressions and chooses
documents that meet the expectation at least one of the expressions.
Syntax:
$exists
The exists operator matches the documents that contain the field when Boolean is true. It
also matches the document where the field value is null.
Syntax:
$type
The type operator chooses documents where the value of the field is an instance of the
specified BSON type.
Syntax:
$expr
The expr operator allows the use of aggregation expressions within the query language.
Syntax:
1. { $expr: { <expression> } }
Example:
$jsonSchema
It matches the documents that satisfy the specified JSON Schema.
Syntax:
$mod
The mod operator selects the document where the value of a field is divided by a divisor
has the specified remainder.
Syntax:
$regex
It provides regular expression abilities for pattern matching strings in queries. The
MongoDB uses regular expressions that are compatible with Perl.
Syntax:
1. { <field>: /pattern/<options> }
Example:
$text
The $text operator searches a text on the content of the field, indexed with a text index.
Syntax:
1. {
2. $text:
3. {
4. $search: <string>,
5. $language: <string>,
6. $caseSensitive: <boolean>,
7. $diacriticSensitive: <boolean>
8. }
9. }
Example:
$where
The "where" operator is used for passing either a string containing a JavaScript expression
or a full JavaScript function to the query system.
Example:
$geoIntersects
It selects only those documents whose geospatial data intersects with the given GeoJSON
object.
Syntax:
1. {
2. <location field>: {
3. $geoIntersects: {
4. $geometry: {
5. type: "<object type>" ,
6. coordinates: [ <coordinates> ]
7. }
8. }
9. }
10. }
Example:
1. db.places.find(
2. {
3. loc: {
4. $geoIntersects: {
5. $geometry: {
6. type: "Triangle" ,
7. coordinates: [
8. [ [ 0, 0 ], [ 3, 6 ], [ 6, 1 ] ]
9. ]
10. }
11. }
12. }
13. }
$geoWithin
The geoWithin operator chooses the document with geospatial data that exists entirely
within a specified shape.
Syntax:
1. {
2. <location field>: {
3. $geoWithin: {
4. $geometry: {
5. type: <"Triangle" or "Rectangle"> ,
6. coordinates: [ <coordinates> ]
7. }
8. }
9. }
$near
The near operator defines a point for which a geospatial query returns the documents from
close to far.
Syntax:
1. {
2. <location field>: {
3. $near: {
4. $geometry: {
5. type: "Point" ,
6. coordinates: [ <longitude> , <latitude> ]
7. },
8. $maxDistance: <distance in meters>,
9. $minDistance: <distance in meters>
10. }
11. }
Example:
1. db.places.find(
2. {
3. location:
4. { $near :
5. {
6. $geometry: { type: "Point", coordinates: [ -73.9667, 40.78 ] },
7. $minDistance: 1000,
8. $maxDistance: 5000
9. }
10. }
11. }
$nearSphere
The nearsphere operator specifies a point for which the geospatial query returns the
document from nearest to farthest.
Syntax:
1. {
2. $nearSphere: [ <x>, <y> ],
3. $minDistance: <distance in radians>,
4. $maxDistance: <distance in radians>
5. }
Example:
1. db.legacyPlaces.find(
2. { location : { $nearSphere : [ -73.9667, 40.78 ], $maxDistance: 0.10 } }
3. )
$all
It chooses the document where the value of a field is an array that contains all the specified
elements.
Syntax:
$elemMatch
The operator relates documents that contain an array field with at least one element that
matches with all the given query criteria.
Syntax:
1. db.books.find(
2. { results: { $elemMatch: { $gte: 500, $lt: 400 } } }
3. )
$size
It selects any array with the number of the element specified by the argument.
Syntax:
$bitsAllClear
It matches the documents where all the bit positions given by the query are clear infield.
Syntax:
1. db.inventory.find( { a: { $bitsAllClear: [ 1, 5 ] } } )
$bitsAllSet
The bitallset operator matches the documents where all the bit positions given by the
query are set in the field.
Syntax:
1. db.inventory.find( { a: { $bitsAllClear: [ 1, 5 ] } } )
$bitsAnyClear
The bitAnyClear operator matches the document where any bit of positions given by the
query is clear in the field.
Syntax:
1. { <field>: { $bitsAnyClear: <numeric bitmask> } }
Example:
1. db.inventory.find( { a: { $bitsAnyClear: [ 5, 10 ] } } )
$bitsAnySet
It matches the document where any of the bit positions given by the query are set in the
field.
Syntax:
1. db.inventory.find( { a: { $bitsAnySet: [ 1, 5 ] } } )
$comment
The $comment operator associates a comment to any expression taking a query
predicate.
Syntax:
1. db.inventory.find(
2. {
3. x: { $mod: [ 1, 0 ] },
4. $comment: "Find Odd values."
5. }
$
The $ operator limits the contents of an array from the query results to contain only the
first element matching the query document.
Syntax:
$elemMatch
The content of the array field made limited using this operator from the query result to
contain only the first element matching the element $elemMatch condition.
Syntax:
$meta
The meta operator returns the result for each matching document where the metadata
associated with the query.
Syntax:
1. { $meta: <metaDataKeyword> }
Example:
1. db.books.find(
2. <query>,
3. { score: { $meta: "textScore" } }
$slice
It controls the number of values in an array that a query returns.
Syntax:
Connection strings
The mongodb driver for Node.js is imported into the code with the require()
function. The object of MongoClient class represents a database connection.
You need to pass a connection string to its constructor.
mongodb://[username:password@]host1[:port1][,...hostN[:portN]][/[defaultauthdb][?options]]
mongodb://localhost:27017/
mongodb+srv://[username:password@]host[/[defaultauthdb][?options]]
const uri =
"mongodb+srv://user:[email protected]/?retryWrites=true&w=majority";
In the following example, we are using the standard connection string to
fetch the list of databases.
main().catch(console.error);
Output
Databases:
- admin
- config
- local
- myProject
- mydb
Explore our latest online courses and learn new skills at your own pace. Enroll
and become a certified expert to boost your career.
The db() method returns a db instance that represents the database on the
server. In the following example, we have demonstrated how to create a new
database named as mydatabase in MongoDB.
try {
// Connect to the MongoDB cluster
await client.connect();
await createdb(client, "mydatabase");
} finally {
// Close the connection to the MongoDB cluster
await client.close();
}
}
main().catch(console.error);
However, note that the database is not physically created on the server till at
least one collection is created and there should be at least one document in
it.