Node.
js - Events
When JavaScript is used inside HTML script, it generally handles the
user-generated events such as button press or mouse clicks. The core
API of [Link] is an asynchronous event-driven architecture. However,
unlike the client-side JavaScript, it handles the events on the server, such
as File io operations, server's request and responses etc.
[Link] identifies several types of events. Each event can be attached to
a callback function. Whenever an event occurs, the callback attached to
it is triggered. The [Link] runtime is always listening to events that may
occur. When any event that it can identify occurs, its attached callback
function is executed.
The [Link] API includes events module, consisting mainly the
EventEmitter class. An EventEmmiter object triggers (or emits) a certain
type of event. You can assign one or more callbacks (listeners) to a
certain type of event. whenever that event triggers, all the registered
callbacks are fired one by one in order to which they were registered.
These are the steps involved in event handling in [Link] API.
First, import the events module, and declare an object of EventEmitter
class
// Import events module
var events = require('events');
// Create an eventEmitter object
var eventEmitter = new [Link]();
Bind an event handler with an event with the following syntax −
// Bind event and event handler as follows
[Link]('eventName', eventHandler);
To fire the event programmatically −
// Fire an event
[Link]('eventName');
Example
Given below is a simple example that binds two listeners to the on event
of EventEmitter class
Open Compiler
// Import events module
var events = require('events');
// Create an eventEmitter object
var eventEmitter = new [Link]();
// Create an event handler as follows
var connectHandler = function connected() {
[Link]('connection successful.');
}
// Bind the connection event with the handler
[Link]('connection', connectHandler);
// Bind the data_received event with the anonymous function
[Link]('data_received', function()
{
[Link]('data received successfully.');});
// Fire the connection event
[Link]('connection');
// Fire the data_received event
[Link]('data_received');
[Link]("Program Ended.");
Output
connection successful.
data received successfully.
Program Ended.
Any asynchronous function in Node Application accepts a callback as the
last parameter. The callback function accepts an error as the first
parameter.
Create a text file named [Link] with the following content.
Tutorials Point is giving self learning content
to teach the world in simple and easy way!!!!!
Create a js file named [Link] having the following code −
var fs = require("fs");
[Link]('[Link]', function (err, data)
{
if (err)
{
[Link]([Link]);
return;
}
[Link]([Link]());});
[Link]("Program Ended");
Here [Link]() is a async function that read a file. If an error occurs
during the read operation, then the err object will contain the
corresponding error, else data will contain the contents of the file. readFile
passes err and data to the callback function after the read operation is
complete, which finally prints the content.
Program Ended
Tutorials Point is giving self learning content
to teach the world in simple and easy way!!!!!
Print Page
[Link] - Event Loop
Even though JavaScript is single threaded, [Link] employs event loop to
perform asynchronous non-blocking I/O operations, by delegating the
operations to the system kernel whenever possible. Most modern OS
kernels are multi-threaded, capable of handling multiple operations by
executing them in the background. When the current operation is
completed, the kernel informs [Link] so that the appropriate callback
may be added to the poll queue to eventually be executed.
The event loop is initialized as soon as [Link] starts, either by providing a
.js script or in REPL mode. The order of operations of the event loop are
shown in the figure below −
The Timers phase executes callbacks scheduled by setTimeout()
and setInterval().
The pending callbacks phase executes I/O callbacks deferred to the
next loop iteration.
The poll phase has two main functions: (a) calculating how long it
should block and poll for I/O, and (b) processing events in the poll
queue. [Link] retrieves new I/O events and executes I/O related
callbacks in this phase.
The check phase executes the callbacks immediately after the poll
phase has completed. If the poll phase becomes idle and scripts
have been queued with setImmediate() timer. The event loop
continues to the check phase rather than waiting. The libuv library
is a part of [Link] runtime, playing the role of providing support for
handling asynchronous operations.
[Link] - Event Emitter
The [Link] API is based on an event-driven architecture. It includes the
events module, which provides the capability to create and handle custom
events. The event module contains EventEmitter class. The EventEmitter
object emits named events. Such events call the listener functions. The
Event Emitters have a very crucial role the [Link] ecosystem. Many
objects in a Node emit events, for example, a [Link] object emits an
event each time a peer connects to it, or a connection is closed. The
[Link] object emits an event when the file is opened, closed, a
read/write operation is performed. All objects which emit events are the
instances of [Link].
Since the EvenEmitter class is defined in events module, we must include
in the code with require statement.
var events = require('events');
To emit an event, we should declare an object of EventEmitter class.
var eventEmitter = new [Link]();
When an EventEmitter instance faces any error, it emits an 'error' event.
When a new listener is added, 'newListener' event is fired and when a
listener is removed, 'removeListener' event is fired.
[Link]
Events & Description
.
newListener(event, listener)
event − String: the event name
1
listener − Function: the event handler function
This event is emitted any time a listener is added. When this event is triggered, the listener ma
not yet have been added to the array of listeners for the event.
2
removeListener(event, listener)
event − String The event name
listener − Function The event handler function
This event is emitted any time someone removes a listener. When this event is triggered, the
listener may not yet have been removed from the array of listeners for the event.
Following instance methods are defined in EventEmitter class −
[Link]
Events & Description
.
addListener(event, listener)
1 Adds a listener at the end of the listeners array for the specified event. Returns emitter, so call
can be chained.
on(event, listener)
2
Adds a listener at the end of the listeners array for the specified event. Same as addListener.
once(event, listener)
3 Adds a one time listener to the event. This listener is invoked only the next time the event is
fired, after which it is removed
removeListener(event, listener)
4 Removes a listener from the listener array for the specified event. If any single listener has bee
added multiple times to the listener array for the specified event, then removeListener must b
called multiple times to remove each instance.
removeAllListeners([event])
5 Removes all listeners, or those of the specified event. It's not a good idea to remove listeners
that were added elsewhere in the code, especially when it's on an emitter that you didn't crea
(e.g. sockets or file streams).
setMaxListeners(n)
6 By default, EventEmitters will print a warning if more than 10 listeners are added for a
particular event. Set to zero for unlimited.
listeners(event)
7
Returns an array of listeners for the specified event.
emit(event, [arg1], [arg2], [...])
8 Execute each of the listeners in order with the supplied arguments. Returns true if the event
had listeners, false otherwise.
off(event, listener)
9
Alias for removeListener
Example
Let us define two listener functions as below −
var events = require('events');
var eventEmitter = new [Link]();
// listener #1
var listner1 = function listner1()
{
[Link]('listner1 executed.');}
// listener #2
var listner2 = function listner2()
{
[Link]('listner2 executed.');}
Let us bind these listeners to a connection event. The first function
listener1 is registered with addListener() method, while we use on()
method to bind listener2.
// Bind the connection event with the listner1 function
[Link]('connection', listner1);
// Bind the connection event with the listner2 function
[Link]('connection', listner2);
// Fire the connection event
[Link]('connection');
When the connection event is fired with emit() method, the console shows
the log message in the listeners as above
listner1 executed.
listner2 executed.
Let us remove the listener2 callback from the connection event, and fire
the connection event again.
// Remove the binding of listner1 function
[Link]('connection', listner1);
[Link]("Listner1 will not listen now.");
// Fire the connection event
[Link]('connection');
The console now shows the following log −
listner1 executed.
listner2 executed.
Listner1 will not listen now.
listner2 executed.
The EventEmitter class also has a listCount() method. It is a class method,
that returns the number of listeners for a given event.
Open Compiler
const events = require('events');
const myEmitter = new [Link]();
// listener #1
var listner1 = function listner1()
{
[Link]('listner1 executed.');}
// listener #2
var listner2 = function listner2()
{
[Link]('listner2 executed.');}
// Bind the connection event with the listner1 function
[Link]('connection', listner1);
// Bind the connection event with the listner2 function
[Link]('connection', listner2);
// Fire the connection event
[Link]('connection');
[Link]("Number of Listeners:" +
[Link]('connection'));
Output
listner1 executed.
listner2 executed.
Number of Listeners:2
The V8 engine handles the execution of JavaScript code, whereas
the Libuv library utilizes the native mechanism of the respective
operating system to hanle asynchronous operations.
Finally, the close callbacks phase handles the callbacks registered
with close event such as [Link](‘close’, function). The close
event will be emitted if the socket is closed abruptly, otherwise it
will be emitted by [Link]() method to defer the execution
of a function until the next iteration of the event loop.
Before beginning the next run of the event loop, [Link] checks if it is
waiting for any asynchronous I/O or timers. If there aren’t any, the runtime
shuts down cleanly.
Understanding how the event loop works is essential for building scalable
[Link] applications. The event loop is a fundamental part of [Link] that
enables asynchronous programming by ensuring the main thread is not
blocked.
UNIT-II
[Link]
JSON stands for JavaScript Object Notation
JSON is a text format for storing and transporting data
JSON is "self-describing" and easy to understand
JSON(JavaScript Object Notation) is a simple and text-
based format for exchanging data between different
applications. Similar to XML, it’s a commonly used method
for web applications and APIs to communicate and share
information.
Below are the different methods to read and write
JSON files:
Table of Content
Using require method
Using the fs module
Note: Reading and writing JSON files in [Link] is crucial
for handling configuration and data storage.
Method 1:
Using require method:
A straightforward way to read a JSON file in a Node JS file is
by using the `require()` method to include it.
Syntax:
const data = require('path/to/file/filename');
Example:
Create a [Link] file in the same directory
where [Link] file present. Add following data to
the [Link] file and write the [Link] file code:
JSON
[
{
"name": "John",
"age": 21,
"language": ["JavaScript", "PHP", "Python"] },
{ "name": "Smith",
"age": 25,
"language": ["PHP", "Go", "JavaScript"] } ]
To run the file using the command:
node [Link]
Output:
Method 2:
Using the fs module:
Another approach to read a file in Node JS is by utilizing the
fs module. The fs module provides the file content as a
string, requiring us to convert it into JSON format using the
built-in method [Link]().
const fs = require("fs");
// Read [Link] file
[Link]("[Link]", function(err, data) {
// Check for errors
if (err) throw err;
// Converting to JSON
const users = [Link](data);
[Link](users); \
// Print users });
Output:
Writing to a JSON file
We can write data into a JSON file by using the
nodejs fs module. We can use writeFile method to write
data into a file.
Syntax:
[Link]("filename", data, callback);
Example:
We will add a new user to the existing JSON file, we have
created in the previous example. This task will be
completed in three steps:
Read the file using one of the above methods.
Add the data using .push() method.
Write the new data to the file
using [Link]() method to convert data into string.
const fs = require("fs");
// STEP 1: Reading JSON file
const users = require("./users");
// Defining new user
let user ={ name: "New User",
age: 30,
language: ["PHP", "Go", "JavaScript"]};
// STEP 2: Adding new data to users object
[Link](user);
// STEP 3: Writing to a file
[Link]( "[Link]",[Link](users),err => {
// Checking for errors
if (err) throw err;
// Success
[Link]("Done writing");
});
Output:
Run the file again and you will see a message into the
console:
Now check your [Link] file it will looks something like
below:
Using the Buffer Module to Buffer Data
What is Buffer in [Link] ?
In Node, Buffer is used to store and manage binary
data. Pure JavaScript is great with Unicode-encoded
strings, but it does not handle binary data very well. It is
not problematic when we perform an operation on data at
the browser level but at the time of dealing with TCP stream
and performing a read-write operation on the file system is
required to deal with pure binary data.
To satisfy this need [Link] uses Buffer to handle the binary
data. So in this article, we are going to know about buffer in
[Link].
What is Buffer in Node?
Buffer in Node is a built-in object used to perform
operations on raw binary data. The buffer class allows
us to handle the binary data directly.
Syntax:
const buf = [Link](10); // Allocates a buffer of
10 bytes.
Generally, Buffer refers to the particular memory
location in memory. Buffer and array have some
similarities, but the difference is array can be any type, and
it can be resizable. Buffers only deal with binary data, and it
can not be resizable. Each integer in a buffer represents a
byte. [Link]() function is used to print the Buffer
instance.
Buffer Methods:
N Method Description
o
1 It creates a buffer and
[Link](size)
allocates size to it.
2 It initializes the buffer
[Link](initialization)
with given data.
3 It writes the data on the
[Link](data)
buffer.
N Method Description
o
4 It read data from the
toString()
buffer and returned it.
5 It checks whether the
[Link](object)
object is a buffer or not.
6 It returns the length of
[Link]
the buffer.
7 [Link](buffer,subsection It copies data from one
size) buffer to another.
8 [Link](start, It returns the subsection
end=[Link]) of data stored in a buffer.
9 It concatenates two
[Link]([buffer,buffer])
buffers.
Example: Basic Implementation of [Link] Buffers
// Filename: [Link]
// Different Method to create Buffer
const buffer1 = [Link](100);
const buffer2 = new Buffer('GFG');
const buffer3 = [Link]([1, 2, 3, 4]);
// Writing data to Buffer
[Link]("Happy Learning");
// Reading data from Buffer
const a = [Link]('utf-8');
[Link](a);
// Check object is buffer or not
[Link]([Link](buffer1));
// Check length of Buffer
[Link]([Link]);
// Copy buffer
const bufferSrc = new Buffer('ABC');
const bufferDest = [Link](3);
[Link](bufferDest);
const Data = [Link]('utf-8');
[Link](Data);
// Slicing dataconst bufferOld = new Buffer('GeeksForGeeks');
const bufferNew = [Link](0, 4);[Link]([Link]());
// concatenate two bufferconst bufferOne = new Buffer('Happy Learning ');const
bufferTwo = new Buffer('With GFG');const bufferThree = [Link]([bufferOne,
bufferTwo]);[Link]([Link]());
Run the [Link] file using the following command:
node [Link]
Output:
Happy Learning
true
100
ABC
Geek
Happy Learning With GFG
Buffers are highly efficient when dealing with large amounts
of binary data or when performance is critical, as they
bypass the overhead of encoding/decoding data into
JavaScript’s native string format.
Accessing the File System from [Link]
[Link] File System
Module
[Link] as a File Server
The [Link] file system module allows you to work with the file system on
your computer.
To include the File System module, use the require() method:
var fs = require('fs');
Common use for the File System module:
Read files
Create files
Update files
Delete files
Rename files
Read Files
The [Link]() method is used to read files on your computer.
Assume we have the following HTML file (located in the same folder
as [Link]):
[Link]
<html>
<body>
<h1>My Header</h1>
<p>My paragraph.</p>
</body>
</html>
Create a [Link] file that reads the HTML file, and return the content:
[Link] URL Module
The Built-in URL Module
The URL module splits up a web address into readable parts.
To include the URL module, use the require() method:
var url = require('url');
Parse an address with the [Link]() method, and it will return a URL
object with each part of the address as properties:
Example
Split a web address into readable parts:
var url = require('url');
var adr = '[Link]
year=2017&month=february';
var q = [Link](adr, true);
[Link]([Link]); //returns 'localhost:8080'
[Link]([Link]); //returns '/[Link]'
[Link]([Link]); //returns '?year=2017&month=february'
var qdata = [Link]; //returns an object: { year: 2017, month:
'february' }
[Link]([Link]); //returns 'february'
Output:
localhost:8080
/default
?year=2017&month=february
february
[Link] Query String
The Query String module used to provides utilities for
parsing and formatting URL query strings. It can be used to
convert query string into JSON object and vice-versa.
[Link] Query String
Query strings in [Link] are a common way to pass data to
a server via a URL. A query string is the part of a URL that
comes after a “?” symbol and contains key-value pairs
separated by &. These strings are used in HTTP requests to
send additional parameters to the server.
The Query String is the part of the URL that starts after the
question mark(?).
mporting Module:
You can include the module using the following code:
const querystring = require('querystring');
Note: It’s not a global object, so need to install it explicitly.
Install Module:
npm install querystring
[Link] Request-Response
Introduction:
The request-response model is the backbone of
how the web works. It's the process that happens
when you visit a website or call an API, with your
browser (or client) asking for something and the
server replying.
What is the Request-Response Pattern?
Client sends a request to the server (think of it
as asking for information).
The server processes the request and sends
back a response (this is the answer).
This pattern is what powers HTTP and makes the web
tick.
Request-Response in [Link]:
[Link] handles this using a non-blocking, event-
driven approach. This makes it fast and efficient even
when dealing with many requests at once.
Here’s how it looks in code:
const http = require('http');
const server = [Link]((req, res) => {
[Link](200, { 'Content-Type': 'text/plain' });
[Link]('Hello, World!\n');});
[Link](3000, () => {
[Link]('Server running at [Link]
Explanation:
The server listens for requests on port 3000.
It responds with "Hello, World!" when a request is
made.
Key Components:
1. Client: Your browser or app sending the request.
2. Request: Contains info like method (GET, POST),
URL, and sometimes data.
3. Server: Where the request goes for processing.
4. Response: What the server sends back (status
code, data, etc.).
[Link] HTTP Module
The Built-in HTTP Module
[Link] has a built-in module called HTTP, which allows [Link] to transfer
data over the Hyper Text Transfer Protocol (HTTP).
To include the HTTP module, use the require() method:
var http = require('http');
[Link] as a Web Server
The HTTP module can create an HTTP server that listens to server ports
and gives a response back to the client.
Use the createServer() method to create an HTTP server:
Example
var http = require('http');
//create a server object:
[Link](function (req, res) {
[Link]('Hello World!'); //write a response to the client
[Link](); //end the response
}).listen(8080); //the server object listens on port 8080
Output:
Hello World!
[Link] OS Module
Definition and Usage
The OS module provides information about the computer's operating
system.
Syntax
The syntax for including the OS module in your application:
var os = require('os');
Example
Get information about the computer's operating system:
var os = require('os');
[Link]("Platform: " + [Link]());
[Link]("Architecture: " + [Link]());
Output:
Platform: win32
Architecture: x64
[Link] Util Module
Definition and Usage
The Util module provides access to some utility functions.
Syntax
The syntax for including the Util module in your application:
var util = require('util');
Util Properties and Methods
Method Description
debuglog() Writes debug messages to the error object
deprecate() Marks the specified function as deprecated
format() Formats the specified string, using the specified arguments
inherits() Inherits methods from one function into another
inspect() Inspects the specified object and returns the object as a string
Run example »
Format a string using the arguments "Linus" and "6":
var util = require('util');
var txt = 'Congratulate %s on his %dth birthday!';
var result = [Link](txt, 'Linus', 6);
[Link](result);
Output:
Congratulate Linus on his 6th birthday!
[Link] DNS Module
Definition and Usage
The DNS module provides a way of performing name resolutions.
Syntax
The syntax for including the DNS module in your application:
var dns = require('dns');
Example
Look up a web address, and write it's IP address:
var dns = require('dns');
var w3 = [Link]('[Link]', function (err, addresses,
family) {
[Link](addresses);
});
Output:
[Link]
[Link] Crypto Module
Definition and Usage
The crypto module provides a way of handling encrypted data.
Syntax
The syntax for including the crypto module in your application:
var crypto = require('crypto');
Crypto Properties and
Methods
Method Description
constants Returns an object containing Crypto Constants
fips Checks if a FIPS crypto provider is in use
createCipher() Creates a Cipher object using the specific algorithm and passw
createCipheriv() Creates a Cipher object using the specific algorithm, password
vector
createDecipher() Creates a Decipher object using the specific algorithm and pass
createDecipheriv() Creates a Decipher object using the specific algorithm, passwo
vector
createDiffieHellman() Creates a DiffieHellman key exchange object
createECDH() Creates an Elliptic Curve Diffie Hellmann key exchange object
createHash() Creates a Hash object using the specified algorithm
createHmac() Creates a Hmac object using the specified algorithm and key
createSign() Creates a Sign object using the specified algorithm and key
createVerify() Creates a Verify object using the specified algorithm
getCiphers Returns an array of supported cipher algorithms
getCurves() Returns an array of supported elliptic curves
getDiffieHellman() Returns a predefined Diffie Hellman key exchange object
getHashes() Returns an array of supported hash algorithms
pbkdf2() Creates a Password Based Key Derivation Function 2 implemen
pbkdf2Sync() Creates a synchronous Password Based Key Derivation Functio
privateDecrypt() Decrypts data using a private key
timingSafeEqual() Compare two Buffers and returns true is they are equal, otherw
privateEncrypt() Encrypts data using a private key
publicDecrypt() Decrypts data using a public key
publicEncrypt() Encrypts data using a public key
randomBytes() Creates random data
setEngine() Sets the engine for some or all OpenSSL function
Example
Encrypt the text 'abc'
var crypto = require('crypto');
var mykey = [Link]('aes-128-cbc', 'mypassword');
var mystr = [Link]('abc', 'utf8', 'hex')
mystr += [Link]('hex');
[Link](mystr); //34feb914c099df25794bf9ccb85bea72
Output:
34feb914c099df25794bf9ccb85bea72
Example
Decrypt back to 'abc'
var crypto = require('crypto');
var mykey = [Link]('aes-128-
cbc', 'mypassword');
var mystr =
[Link]('34feb914c099df25794bf9ccb85bea72', 'hex', 'utf8'
)
mystr += [Link]('utf8');
[Link](mystr); //abc
Output:
abc
Unit-III
MongoDB
MongoDB is a general-purpose document database designed for modern
application development and for the cloud. Its scale-out architecture allows
you to meet the increasing demand for your system by adding more nodes to
share the load.
Key Aspects of MongoDB
Here are some of the key concepts and terms you will encounter as you learn
about MongoDB.
Documents: The records in a document database
Collections: Grouping documents
Replica sets: Ensuring high availability
Sharding: Scalability to handle massive data growth
Indexes: Improving query speed
Aggregation pipelines: Fast data flows
Programming languages: Does MongoDB speak your language?
How to monitor MongoDB
MongoDB cloud
Documents: The Records in a document
database
MongoDB stores data as JSON documents.
The document data model maps naturally to objects in application code,
making it simple for developers to learn and use.
The fields in a JSON document can vary from document to document.
Compare that to a traditional relational database table, where adding a field
means adding a column to the database table itself and therefore to every
record in the database.
Documents can be nested to express hierarchical relationships and store
structures such as arrays.
The document model provides flexibility to work with complex, fast-changing,
messy data from numerous sources. It enables developers to quickly deliver
new application functionality.
For faster access internally and to support more data types, MongoDB
converts documents into a format called Binary JSON or BSON. But from a
developer perspective, MongoDB is a JSON database.
Collections: Grouping Documents
In MongoDB, a collection is a group of documents.
If you are familiar with relational databases, you can think of a collection as a
table. But collections in MongoDB are far more flexible. Collections do not
enforce a schema unless you configure them to, and documents in the same
collection can have different fields.
Each collection is associated with one MongoDB database. To show which
collections are in a particular database, use the command listCollections.
Replica sets: Ensuring high availability
An important way to ensure high availability is by keeping more than one copy
of your data. With MongoDB, high availability is built right into the design.
When you create a database in MongoDB, the system automatically creates
at least two more copies of the data, referred to as a replica set. A replica set
is a group of at least three MongoDB instances that continuously replicate
data between them, offering redundancy and protection against downtime in
the face of a system failure or planned maintenance.
Sharding: Scalability to handle massive data
growth
A modern data platform needs to be able to handle very fast queries and
massive datasets using ever bigger clusters of small machines. Sharding is
the term for distributing data intelligently across multiple machines.
How does sharding work in MongoDB? MongoDB shards data at the
collection level, distributing documents in a collection across the shards in a
cluster. The result is a scale-out architecture that supports even the largest
applications.
Indexes: Improving query speed
Indexes support the efficient execution of queries. MongoDB offers a variety
of different indexing strategies, including compound indexes on multiple fields.
Chosen carefully, indexes speed up queries because queries scan
the index instead of reading every document in the collection.
There is still work to do to analyze which queries could benefit from adding an
index. One tool that does this analysis for you is Performance Advisor, which
analyzes queries and suggests indexes that would improve query
performance.
Aggregation pipelines: Fast data flows
MongoDB offers a flexible framework for creating data processing pipelines
called aggregation pipelines. It features dozens of stages and over 150
operators and expressions, enabling you to process, transform, and analyze
data of any structure at scale. One recent addition is the Union stage, which
flexibly aggregates results from multiple collections.
Programming languages: Does MongoDB speak
your language?
What languages can you use with MongoDB? The list of supported
languages includes [Link], C, C++, C#, Go, Java, Perl, PHP, Python, Ruby,
Rust, Scala, Swift and many more. The library for each language is actively
maintained, which means that it is updated with new features, bug fixes,
security patches, and performance enhancements.
How to monitor MongoDB
You can monitor your cluster's health and performance by checking instance
status, cluster operations and connections metrics, hardware metrics, and
more with just a few utilities and commands. Monitoring can help you detect
and react to real-time issues before they become significant.
MongoDB cloud
MongoDB started out as an open source database and it still can be used that
way through the MongoDB Community Edition.
In MongoDB Enterprise Edition, advanced features are available through a
commercial license.
MongoDB Atlas is a database-as-a-service (DBaaS) version of MongoDB
Enterprise Edition that is offered on all public clouds.
MongoDB Atlas has been extended in a variety of ways with built-in, tightly
integrated functionality such as Atlas Search, Atlas Vector Search, and other
advanced features for geo-locating data and making backups.
Mongodb Data Types
MongoDB stores data using BSON, which supports additional data types that
aren't available in JSON. The mongosh shell has better data type support
for drivers than the legacy mongo shell.
This document highlights changes in type usage between mongosh and the
legacy mongo shell. See the Extended JSON reference for additional
information on supported types.
String − This is the most commonly used datatype to store the data.
String in MongoDB must be UTF-8 valid.
Integer − This type is used to store a numerical value. Integer can be 32
bit or 64 bit depending upon your server.
Boolean − This type is used to store a boolean (true/ false) value.
Double − This type is used to store floating point values.
Min/ Max keys − This type is used to compare a value against the lowest
and highest BSON elements.
Arrays − This type is used to store arrays or list or multiple values into
one key.
Timestamp − ctimestamp. This can be handy for recording when a
document has been modified or added.
Object − This datatype is used for embedded documents.
Null − This type is used to store a Null value.
Symbol − This datatype is used identically to a string; however, it's
generally reserved for languages that use a specific symbol type.
Date − This datatype is used to store the current date or time in UNIX
time format. You can specify your own date time by creating object of
Date and passing day, month, year into it.
Object ID − This datatype is used to store the documents ID.
Binary data − This datatype is used to store binary data.
Code − This datatype is used to store JavaScript code into the document.
Regular expression − This datatype is used to store regular expression.
MongoDB - Data Modelling
MongoDB provides two types of data models: Embedded data model and
Normalized data model. Based on the requirement, you can use either of the models
while preparing your document.
Embedded Data Model
In this model, you can have (embed) all the related data in a single document, it is
also known as de-normalized data model.
For example, assume we are getting the details of employees in three different
documents namely, Personal_details, Contact and, Address, you can embed all the
three documents in a single one as shown below −
{
_id: ,
Emp_ID: "10025AE336"
Personal_details:{
First_Name: "Radhika",
Last_Name: "Sharma",
Date_Of_Birth: "1995-09-26"
},
Contact: {
e-mail: "radhika_sharma.123@[Link]",
phone: "9848022338"
},
Address: {
city: "Hyderabad",
Area: "Madapur",
State: "Telangana"
}}
Normalized Data Model
In this model, you can refer the sub documents in the original document, using
references. For example, you can re-write the above document in the normalized
model as:
Employee:
{
_id: <ObjectId101>,
Emp_ID: "10025AE336"}
Personal_details:
{
_id: <ObjectId102>,
empDocID: " ObjectId101",
First_Name: "Radhika",
Last_Name: "Sharma",
Date_Of_Birth: "1995-09-26"}
Contact:
{
_id: <ObjectId103>,
empDocID: " ObjectId101",
e-mail: "radhika_sharma.123@[Link]",
phone: "9848022338"}
Address:
{
_id: <ObjectId104>,
empDocID: " ObjectId101",
city: "Hyderabad",
Area: "Madapur",
State: "Telangana"}
Building the MongoDB Environment:
To get started with MongoDB, you have to install it in your system. You need to find
and download the latest version of MongoDB, which will be compatible with your
computer system. You can use this ([Link] link and
follow the instruction to install MongoDB in your PC. In this chapter, you will learn
how to setup a complete environment to start working with MongoDB.
The process of setting up MongoDB in different operating systems is
also different, here various installation steps have been mentioned
and according to your convenience, you can select it and follow it.
Install MongoDB in Windows
The website of MongoDB provides all the installation instructions,
and MongoDB is supported by Windows, Linux as well as Mac OS.
It is to be noted that, MongoDB will not run in Windows XP; so you
need to install higher versions of windows to use this database.
Once you visit the link ([Link]
Once the download is complete, double click this setup file to install
it. Follow the steps:
1. Click Next.
2. Now, choose Complete to install MongoDB completely.
3. Then, select the radio button "Run services as Network service
user."
4. The setup system will also prompt you to install MongoDB
Compass, which is MongoDB official graphical user interface
(GUI). You can tick the checkbox to install that as well.
Once the installation is done completely, you need to start MongoDB
and to do so follow the process:
1. Open Command Prompt.
2. Type: C:\Program Files\MongoDB\Server\4.0\bin
3. Now type the command simply: mongod to run the server.
In this way, you can start your MongoDB database. Now, for running
MongoDB primary client system, you have to use the command:
C:\Program Files\MongoDB\Server\4.0\bin>[Link]
Create User and Add Role in
MongoDB
Access control is one of the most important aspects of
database security. In MongoDB, user creation and role
assignment help define who can access the database and
what actions they are allowed to perform. MongoDB’s built-
in user management system allows administrators to
control user privileges, ensuring data
security and integrity. By creating users with specific
roles and permissions, we can manage access to your
MongoDB instance effectively.
In this article, we will explain how to create users, assign
them roles, and configure authentication in MongoDB.
This will provide us with the tools to set up proper access
control and security measures for our database.
What is User Creation and Role
Assignment in MongoDB?
In MongoDB, we are allowed to create new users for the
database. Every MongoDB user only accesses the data that
is required for their role. A role in MongoDB grants
privileges to perform some set of operations on a given
resource. In MongoDB, users are created
using createUser() method. This method creates a new
user for the database, if the specified user is already
present in the database then this method will return an
error.
Users in MongoDB
A user in MongoDB is an entity that is granted access to
one or more databases. Users must authenticate using valid
credentials before they are allowed to execute operations
on the database. Users can have varying levels of access
depending on the roles assigned to them.
Roles in MongoDB
A role in MongoDB defines a set of privileges or actions
that a user is allowed to perform. MongoDB provides
several built-in roles such as read, readWrite, and dbAdmin.
These roles grant users permissions to perform certain
operations on specific resources like collections or
databases.
How to Create a User and Assign Roles
in MongoDB
MongoDB provides the createUser() method, which allows you
to create new users and assign them specific roles. These
roles determine what actions a user can perform within the
database.
Syntax:
[Link]({
user: “<username>”, // User’s name
pwd: “<password>”, // User’s password
roles: [ // Roles assigned to the user
{ role: “<role_name>”, db: “<db_name>” }
]
})
Access control is one of the most important aspects of
database security. In MongoDB, user creation and role
assignment help define who can access the database and
what actions they are allowed to perform. MongoDB’s built-
in user management system allows administrators to
control user privileges, ensuring data
security and integrity. By creating users with specific
roles and permissions, we can manage access to your
MongoDB instance effectively.
In this article, we will explain how to create users, assign
them roles, and configure authentication in MongoDB.
This will provide us with the tools to set up proper access
control and security measures for our database.
What is User Creation and Role
Assignment in MongoDB?
In MongoDB, we are allowed to create new users for the
database. Every MongoDB user only accesses the data that
is required for their role. A role in MongoDB grants
privileges to perform some set of operations on a given
resource. In MongoDB, users are created
using createUser() method. This method creates a new
user for the database, if the specified user is already
present in the database then this method will return an
error.
Users in MongoDB
A user in MongoDB is an entity that is granted access to
one or more databases. Users must authenticate using valid
credentials before they are allowed to execute operations
on the database. Users can have varying levels of access
depending on the roles assigned to them.
Roles in MongoDB
A role in MongoDB defines a set of privileges or actions
that a user is allowed to perform. MongoDB provides
several built-in roles such as read, readWrite, and dbAdmin.
These roles grant users permissions to perform certain
operations on specific resources like collections or
databases.
How to Create a User and Assign Roles
in MongoDB
MongoDB provides the createUser() method, which allows you
to create new users and assign them specific roles. These
roles determine what actions a user can perform within the
database.
Syntax:
[Link]({
user: “<username>”, // User’s name
pwd: “<password>”, // User’s password
roles: [ // Roles assigned to the user
{ role: “<role_name>”, db: “<db_name>” }
]
})
Key Terms
user: The name of the user you are creating. This will be
used for authentication.
pwd: The password for the user. This field is required
unless you are creating a user in an external database
(using $external).
roles: The access levels and privileges that the user will
have. This is an array where you specify the roles
assigned to the user.
o Role Name: A built-in role
like read, readWrite, dbAdmin, etc.
o Custom Roles: You can also create your own
custom roles using the [Link]() method.
authenticationRestrictions: This optional field defines
the restrictions for user authentication, such as limiting
access to certain IP addresses or client sources.
mechanisms: This optional field specifies
which SCRAM (Salted Challenge-Response
Authentication Mechanism) method to use, if applicable.
passwordDigestor: This optional field is used to check
how the password is digested, either by the server or
client.
writeConcern: This optional field defines the level of
write concern for the operation, which determines how
the system handles write operations and error reporting.
1. Create An Administrative User
In MongoDB, you can create an administrative user using
the createUser() method. In this method, we can create the
name, password, and roles of an administrative user. Let us
discuss this concept with the help of an example:
Example:
In this example, we are going to create an administrative
user in the admin database and gives the user readWrite
access to the config database which lets the user change
certain settings for sharded clusters.
Query:
[Link](
{
user: "hello_admin",
pwd: "hello123",
roles:
[
{ role:"readWrite",db:"config"},
"clusterAdmin"
] } );
So to create an administrative user first we use the admin
database. In this database, we create an admin user using
the createUser() method. In this method, we set the user
name is “hello_admin”, password is “hello123” and the
roles of the admin user are readWrite, config,
clusterAdmin.
Output
2. Create A Normal User Without Any Roles
In MongoDB, we can create a user without any roles by
specifying an empty array[] in the role field in createUser()
method. Let us discuss this concept with the help of an
example:
Syntax:
[Link]({ user:”User_Name”,
pwd:”Your_Password”, roles:[]});
Example:
In the following example, we are going to create a user
without roles. Here, we are working on the “example”
database and created a user named “geeks” without roles.
[Link]({user:"geeks", pwd: "computer", roles:
[]});
Output
3. Create A User With Some Specifying Roles
In MongoDB, we can create a user with some specified
roles using the createUser() method. In this method, we can
specify the roles that the user will do after creating. Let us
discuss this concept with the help of an example:
Example:
In this example, we are going to create a user with some
specified roles.
[Link](
...{
...user: "new_one_role",
...pwd: with_roles",
...roles:["readWrite", "dbAdmin"]
...}
...);
Here, we create a user whose name is “new_one_role”,
password is “with_roles” and the specified roles are:
readWrite Role: This role provides all the privileges of the
read role plus the ability to modify data on all non-
system collections.
dbAdmin Role: This role gives the ability to the user to
perform administrative tasks such as schema-related
tasks, indexing. It does not grant privileges for the User
and Role Management.
Output
4. Create A User For A Single Database
In MongoDB, we can also create a user for single database
using createUser() method. Let us discuss this concept with
the help of an example:
Example:
[Link](
{
user: "robert",
pwd: "hellojose",
roles:[{role: "userAdmin" , db:"example"}]})
Here, we create a user whose user name is “Robert”,
password is “hellojose”, and we assign a role for the user
which in this case needs to be a database administrator so
it is assigned to the “userAdmin” role. This role will allow
the user to have administrative privileges only to the
database specified in the db option, i.e., “example”.
Output:
Create Users with Authentication
Restrictions
In MongoDB, authentication is a process which checks
whether the user/client who is trying to access the
database is known or unknown. If the user is known then it
allows them to connect with server. We can also create a
user with authentication restrictions using createUser()
method by setting the value of authenticationRestrictions
field. This field provides authentication permission of the
user and contains the following fields:
1. clientSource: If the value of this field is present, so
when a user is authenticating the server verifies the client
IP by checking the IP address in the given list or CIDR range
in the list. If the client IP present in the list then the server
authenticate the client or if not then server will not
authenticate the user.
2. serverAddress: It is a list of IP addresses or CIDR
ranges to which the client can connect. If the value of this
field is present in the list, then the server verify the client
connection and if the connection was established via
unrecognized IP address, then the server does not
authenticate the user.
Let us discuss this concept with the help of an example:
Example:
In this example, we are going to create a user with
authentication restrictions:
use admin
[Link](
{
user: "restrict",
pwd: passwordPrompt(),
roles: [ { role: "readWrite", db: "example" } ],
authenticationRestrictions: [ {
clientSource: ["[Link]"],
serverAddress: ["[Link]"]
} ]
}
)
Here we create a user named “restrict” in the admin
database. So this user may only authenticate if connecting
from IP address [Link] to this server address IP
address [Link].
Output
How To Drop A User in MongoDB
In Mongodb, we can also drop a user using dropUser()
method. This method returns true when the user is deleted
otherwise return false.
Syntax:
[Link](“Username”)
Example:
In this example, we will drop a user whose name is Robert.
[Link]("robert")
Output:
Drop User
Conclusion
In MongoDB, managing users and roles is important for
maintaining data security and access control. By utilizing
the createUser() method, administrators can define
user credentials, roles, and authentication restrictions
customized to their organizational needs. This ensures that
MongoDB deployments are secure and users have
appropriate access to perform their tasks effectively. By
understanding and implementing MongoDB’s user and role
management system, we can strengthen your security
posture, ensure data integrity, and meet compliance
requirements.
So to create an administrative user first we use the admin
database. In this database, we create an admin user using
the createUser() method. In this method, we set the user
name is “hello_admin”, password is “hello123” and the
roles of the admin user are readWrite, config,
clusterAdmin.
Output
2. Create A Normal User Without Any Roles
In MongoDB, we can create a user without any roles by
specifying an empty array[] in the role field in createUser()
method. Let us discuss this concept with the help of an
example:
Syntax:
[Link]({ user:”User_Name”,
pwd:”Your_Password”, roles:[]});
Example:
In the following example, we are going to create a user
without roles. Here, we are working on the “example”
database and created a user named “geeks” without roles.
[Link]({user:"geeks", pwd: "computer", roles:
[]});
Output
3. Create A User With Some Specifying Roles
In MongoDB, we can create a user with some specified
roles using the createUser() method. In this method, we can
specify the roles that the user will do after creating. Let us
discuss this concept with the help of an example:
Example:
In this example, we are going to create a user with some
specified roles.
[Link](
...{
...user: "new_one_role",
...pwd: with_roles",
...roles:["readWrite", "dbAdmin"]
...}
...);
Here, we create a user whose name is “new_one_role”,
password is “with_roles” and the specified roles are:
readWrite Role: This role provides all the privileges of the
read role plus the ability to modify data on all non-
system collections.
dbAdmin Role: This role gives the ability to the user to
perform administrative tasks such as schema-related
tasks, indexing. It does not grant privileges for the User
and Role Management.
Output
4. Create A User For A Single Database
In MongoDB, we can also create a user for single database
using createUser() method. Let us discuss this concept with
the help of an example:
Example:
[Link](
{
user: "robert",
pwd: "hellojose",
roles:[{role: "userAdmin" , db:"example"}]})
Here, we create a user whose user name is “Robert”,
password is “hellojose”, and we assign a role for the user
which in this case needs to be a database administrator so
it is assigned to the “userAdmin” role. This role will allow
the user to have administrative privileges only to the
database specified in the db option, i.e., “example”.
Output:
Create Users with Authentication
Restrictions
In MongoDB, authentication is a process which checks
whether the user/client who is trying to access the
database is known or unknown. If the user is known then it
allows them to connect with server. We can also create a
user with authentication restrictions using createUser()
method by setting the value of authenticationRestrictions
field. This field provides authentication permission of the
user and contains the following fields:
1. clientSource: If the value of this field is present, so
when a user is authenticating the server verifies the client
IP by checking the IP address in the given list or CIDR range
in the list. If the client IP present in the list then the server
authenticate the client or if not then server will not
authenticate the user.
2. serverAddress: It is a list of IP addresses or CIDR
ranges to which the client can connect. If the value of this
field is present in the list, then the server verify the client
connection and if the connection was established via
unrecognized IP address, then the server does not
authenticate the user.
Let us discuss this concept with the help of an example:
Example:
In this example, we are going to create a user with
authentication restrictions:
use admin
[Link](
{
user: "restrict",
pwd: passwordPrompt(),
roles: [ { role: "readWrite", db: "example" } ],
authenticationRestrictions: [ {
clientSource: ["[Link]"],
serverAddress: ["[Link]"]
} ]
}
)
Here we create a user named “restrict” in the admin
database. So this user may only authenticate if connecting
from IP address [Link] to this server address IP
address [Link].
Output
How To Drop A User in MongoDB
In Mongodb, we can also drop a user using dropUser()
method. This method returns true when the user is deleted
otherwise return false.
Syntax:
[Link](“Username”)
Example:
In this example, we will drop a user whose name is Robert.
[Link]("robert")
Output:
Drop User
Conclusion
In MongoDB, managing users and roles is important for
maintaining data security and access control. By utilizing
the createUser() method, administrators can define
user credentials, roles, and authentication restrictions
customized to their organizational needs. This ensures that
MongoDB deployments are secure and users have
appropriate access to perform their tasks effectively. By
understanding and implementing MongoDB’s user and role
management system, we can strengthen your security
posture, ensure data integrity, and meet compliance
requirements.
Configuring Access Control :
What is Authentication in MongoDB?
Authentication in MongoDB is the process of verifying the
identity of users or applications attempting to access
the database. It ensures that only authorized individuals
can access sensitive data by requiring them to provide
valid credentials such as a username and password.
When authentication is enabled, MongoDB will require
users to authenticate themselves before being allowed
access to databases. It is crucial in maintaining
the security and integrity of the data, especially in
environments with multiple users or applications.
Why is Authentication Important in
MongoDB?
Authentication is essential to build industry-
grade database systems. Authentication helps to maintain
the security and integrity of the Database. Without
authentication, anyone who can connect to your MongoDB
instance can potentially modify or delete data, leading
to data breaches or unauthorized changes.
Prevents Unauthorized Access: Ensures that only
users with valid credentials can access and modify the
database.
Protects Sensitive Data: Helps safeguard sensitive
information such as customer data, financial records,
and intellectual property.
Ensures Data Integrity: Reduces the risk of accidental
or malicious data tampering or loss.
Compliance: Meets security and compliance standards
(e.g., GDPR, HIPAA) that require authentication for data
protection.
For example: We can think of data as money and
databases as Banks. So now if anyone can access the bank
locker without any validation then there is always a concern
about the money in the bank. One can steal it, take some
money from another account holder without knowledge,
etc. So, we must define access control and authentication.
Steps to Enable Access Control and
Authentication in MongoDB
To secure your MongoDB instance, follow these steps in
the specified order to successfully enable authentication
and access control.
Step 1: Start the MongoDB
To make changes in MongoDB, we need to start the
MongoDB server. To start MongoDB, open the command
prompt on our computer and execute the following
command to start MongoDB.
mongosh
Output:
Connect to MongoDB
As we can see that the database has been started and we
can access it.
Step 2: Create a Database and Add Documents
Now to create database, we can manually write all details in
command prompt or we can use MongoDB Compass to
use the GUI. Let's quickly create a database in MongoDB
and add some documents in it.
First use a database name to use the database. It will not
instantly create the Database, as we create a Collection,
the database will be created.
use mydb //Creates database
[Link]("nameColletion")
Output:
Create Collection
Once we have successfully created a database, it's time to
insert few documents into the database.
[Link]({ name: "Philips Kumar",
age: 21})
Output:
Insert Documents
Now using the same format, we can insert more data in the
database as per our requirements. Use the article on How
to Create Database & Collection in MongoDB for better
understanding.
Step 3: Create User
To use authentication, we need to define a user and
assign certain role to it. Lets create a user
named Geek and assign the role of useradmin for the
database mydb. The useradmin role provides the user
with power to create new users and assign roles to
others including self.
This user can access, update or delete any data in the
database. If short, we are giving the superuser role to the
user named Geek. However, The privileges of the user
stays only inside the database defined.
[Link]({
... "user": "Geek",
... "pwd": "abc123",
... "roles": [ { "role": "userAdmin", "db": "mydb" }
]
... })
Output:
Create User
Step 4: Change MongoDB Configuration to
Enable Authentication
By default, in MongoDB the authentication feature is not
enable. So, to use authentication we first have to edit the
configurations and enable access control. To do that,
navigate to the [Link] file. The path to the file
should be similar to the following,
C:\Program Files\MongoDB\Server\7.0\bin
Open the [Link] file in any editor and write the
following under security,
security:
authentication: enabled
Save the changes and close the file. Once we have made
the changes, Go to Services in Windows and
find MongoDB and restart it.
Step 5: Authenticate with the Created User
Once restarted, now try accessing the data we have
inserted without authenticating with valid credentials. Let's
ask the database to show all documents available in the
collection nameCollection.
[Link]()
Output:
require authentication
As we can see it is saying that we need to autheticate first
to get the data. That means we have successfully enable
authentication and access control.
Now to see the data, let's first give
the username and password.
[Link]("Geek","abc123")
Output:
Give user and
Password
Now check for the available documents in the database.
[Link]()
Output:
As we can see after successful authentication, we get
access to the documents available in the MongoDB
database.
Conclusion
Authentication is needed everywhere if there exists
sensitive data. Follow the above given steps in the order to
successfully implement Access Control and Authentication
in MongoDB server. The order of steps should be
maintained, otherwise we may face some errors. If we
change the configuration file before creating user then we
will not be able to access the database. Also make sure to
create the database Admin before you start following the
steps. As if any issues encountered, you can use it's
privileges to add new users and modify roles and
databases.
Securing our database is very important to protect our
data. MongoDB, being one of the most popular NoSQL
databases, provides robust security features like access
control and user authentication to prevent unauthorized
access and data breaches. Enabling authentication in
MongoDB ensures that only authorized users can interact
with the database, keeping our data safe.
In this article, we will be learning about how we can set
up access control and authentication for MongoDB
servers. These practices are essential for ensuring data
integrity, privacy, and protecting your MongoDB
database from unauthorized actions.
Administering Databases
Administering databases in MongoDB involves a range of tasks aimed at
ensuring data reliability, performance, and security. Here's a brief
overview of key responsibilities and best practices:
🔧 Core Administrative Tasks
[Link] Modeling: Designing schemas that optimize performance and scalability.
MongoDB's flexible schema allows embedding documents or using references,
depending on access patterns.
[Link] Operations: Managing data through Create, Read, Update, and
Delete operations using methods like insertOne(), find(), updateOne(), and
deleteOne(). MongoDB also supports atomic transactions for multi-document
operations.
[Link]: Creating indexes to improve query performance. MongoDB
supports various index types, including compound, geospatial, and text
indexes.
[Link] and Restore: Implementing strategies like mongodump and
snapshots to protect data and ensure quick recovery.
Monitoring and Performance Tuning: Utilizing tools like MongoDB Atlas and
the Database Profiler to monitor performance and optimize queries.
🔐 Security Best Practices
Authentication and Authorization: Enabling authentication and assigning
roles such as readWrite, dbAdmin, and dbOwner to control access.
Data Encryption: Using TLS/SSL for data in transit and enabling encryption at
rest to protect sensitive information.
Compliance and Auditing: Implementing regular audits and compliance
checks to adhere to industry standards.
🧩 Tools and Interfaces
MongoDB Shell: A command-line interface for direct interaction with the
database.
MongoDB Compass: A GUI for visualizing and managing data, indexes, and
performance metrics
MongoDB Atlas: A fully managed cloud service offering automated backups,
scaling, and monitoring.
Managing Collections
MongoDB is a popular NoSQL database that offers a flexible, scalable,
and high-performance way to store data. In
MongoDB, Databases, Collections, and Documents are the fundamental
building blocks for data storage and management. Understanding these
components is crucial for efficiently working with MongoDB.
What is a Database in MongoDB?
A Database in MongoDB is a container for data that holds multiple
collections. MongoDB allows the creation of multiple databases on a
single server, enabling efficient data organization and management for
various applications. It’s the highest level of structure within
the MongoDB system.
1. Multiple Databases: MongoDB allows you to create multiple databases
on a single server. Each database is logically isolated from others.
2. Default Databases: When you start MongoDB, three default databases
are created: admin, config, and local. These are used for internal purposes.
3. Database Creation: Databases are created when you insert data into
them. You can create or switch to a database using the following
command:
use <database_name>
This command actually switches you to the new database if the given
name does not exist and if the given name exists, then it will switch you to
the existing database. Now at this stage, if you use the show command to
see the database list where you will find that your new database is not
present in that database list because, in MongoDB, the database is actually
created when we start entering data in that database.
4. View Database: To see how many databases are present in your
MongoDB server, write the following statement in the mongo shell:
show dbs
Here, we freshly started MongoDB so we do not have a database except
these three default databases, i.e, admin, config, and local.
Here, we create a new database named GeeksforGeeks using the use
command. After creating a database when we check the database list we do
not find our database on that list because we do not enter any data in
the GeeksforGeeks database.
Naming Restriction for Database:
Before creating a database we should first learn about the naming
restrictions for databases:
Database names must be case-insensitive.
The names cannot contain special characters such as /, ., $, *, |, etc.
MongoDB database names cannot contain null characters(in windows,
Unix, and Linux systems).
MongoDB database names cannot be empty and must contain less than
64 characters.
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.
>[Link]({"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 [Link]() command is used to drop a existing
database.
Syntax
Basic syntax of dropDatabase() command is as follows −
[Link]()
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
>[Link]()
>{ "dropped" : "mydb", "ok" : 1 }
>
Now check list of databases.
>show dbs
local 0.78125GB
test 0.23012GB
>
What is a Collection in MongoDB?
A Collection in MongoDB is similar to a table in relational
databases. It holds a group of documents and is a part of a
database. Collections provide structure to data, but like the
rest of MongoDB, they are schema-less.
Schemaless
As we know that MongoDB databases are schemaless.
So, it is not necessary in a collection that the schema of
one document is similar to another document. Or in other
words, a single collection contains different types of
documents like as shown in the below example
where mystudentData collection contain two different
types of documents:
Multiple Collections per Database
A single database can contain multiple collections, each
storing different types of documents.
Create Collection
using mongosh
here are 2 ways to create a collection.
Method 1
You can create a collection using the createCollection() database
method.
Example
[Link]("posts")
Method 2
You can also create a collection during the insert process.
Example
We are here assuming object is a valid JavaScript object containing post data:
[Link](object)
Examples
Basic syntax of createCollection() method without options is as follows
−
>use test
switched to db test
>[Link]("mycollection"){ "ok" : 1 }
>
You can check the created collection by using the command show
collections.
>show collections
mycollection
[Link]
In MongoDB, you don't need to create collection. MongoDB creates
collection automatically, when you insert some document.
>[Link]({"name" : "tutorialspoint"}),
WriteResult({ "nInserted" : 1 })
>show collections
mycol
mycollection
[Link]
tutorialspoint
>
What is a Document in MongoDB?
In MongoDB, the data records are stored as BSON
documents. Here, BSON stands for binary representation
of JSON documents, although BSON contains more data
types as compared to JSON. The document is created
using field-value pairs or key-value pairs and the value
of the field can be of any BSON type.
Syntax:
{
field1: value1
field2: value2
….
fieldN: valueN
}
Document Structure:
A document in MongoDB is a flexible data structure made
up of field-value pairs. For instance:
{
title: "MongoDB Basics",
author: "John Doe",
year: 2025
}
MongoDB mongosh Inse
rt
Insert Documents
There are 2 methods to insert documents into a MongoDB database.
insertOne()
To insert a single document, use the insertOne() method.
This method inserts a single object into the database.
Note: When typing in the shell, after opening an object with curly braces "{" you
can press enter to start a new line in the editor without executing the command.
The command will execute when you press enter after closing the braces.
Example
[Link]({
title: "Post Title 1",
body: "Body of post.",
category: "News",
likes: 1,
tags: ["news", "events"],
date: Date()})
Note: If you try to insert documents into a collection that does not exist, MongoDB
will create the collection automatically.
insertMany()
To insert multiple documents at once, use the insertMany() method.
This method inserts an array of objects into the database.
Example
[Link]([
title: "Post Title 2",
body: "Body of post.",
category: "Event",
likes: 2,
tags: ["news", "events"],
date: Date()
},
title: "Post Title 3",
body: "Body of post.",
category: "Technology",
likes: 3,
tags: ["news", "events"],
date: Date()
},
title: "Post Title 4",
body: "Body of post.",
category: "Event",
likes: 4,
tags: ["news", "events"],
date: Date()
}])
MongoDB mongosh Find
Find Data
There are 2 methods to find and select data from a MongoDB
collection, find() and findOne().
find()
To select data from a collection in MongoDB, we can use
the find() method.
This method accepts a query object. If left empty, all documents will be
returned.
Example
[Link]()
findOne()
To select only one document, we can use the findOne() method.
This method accepts a query object. If left empty, it will return the first
document it finds.
Note: This method only returns the first match it finds.
Example
[Link]()
Querying Data
To query, or filter, data we can include a query in
our find() or findOne() methods.
Example
[Link]( {category: "News"} )
MongoDB mongosh Upd
ate
Update Document
To update an existing document we can use
the updateOne() or updateMany() methods.
The first parameter is a query object to define which document or
documents should be updated.
The second parameter is an object defining the updated data.
updateOne()
The updateOne() method will update the first document that is found
matching the provided query.
Let's see what the "like" count for the post with the title of "Post Title 1":
Example
[Link]( { title: "Post Title 1" } )
Output:
[
{
_id: ObjectId("62c350dc07d768a33fdfe9b0"),
title: 'Post Title 1',
body: 'Body of post.',
category: 'News',
likes: 1,
tags: [ 'news', 'events' ],
date: 'Mon Jul 04 2022 15:43:08 GMT-0500 (Central Daylight
Time)'
}
]
[Link]( { title: "Post Title 1" } )
[
{
_id: ObjectId("62c350dc07d768a33fdfe9b0"),
title: 'Post Title 1',
body: 'Body of post.',
category: 'News',
likes: 2,
tags: [ 'news', 'events' ],
date: 'Mon Jul 04 2022 15:43:08 GMT-0500 (Central Daylight
Time)'
}
]
updateMany()
The updateMany() method will update all documents that match the
provided query.
Example
Update likes on all documents by 1. For this we will use the $inc (increment)
operator:
[Link]({}, { $inc: { likes: 1 } })
Delete Documents
We can delete documents by using the
methods deleteOne() or deleteMany().
These methods accept a query object. The matching documents will be
deleted.
deleteOne()
The deleteOne() method will delete the first document that matches the
query provided.
Example
[Link]({ title: "Post Title 5" })
deleteMany()
The deleteMany() method will delete all documents that match the query
provided.
Example
[Link]({ category: "Technology" })
Adding the MongoDB Driver to [Link]
1. Install the MongoDB [Link] Driver
Ensure you have [Link] version 16.20.1 or later installed. Then, in your project
directory, run
npm install mongodb@6.16
This command installs the MongoDB driver and saves it as a
dependency in your [Link] file.
2. Set Up Your Project
Create a new directory for your project and initialize it:
mkdir node_quickstart
cd node_quickstart
npm init -y
his initializes a new [Link] project and creates a [Link] file.
3. Install the MongoDB Driver
Install the official MongoDB [Link] driver:
npm install mongodb@6.14
This command downloads the mongodb package and its
dependencies, saving them in the node_modules directory and
recording the dependency in your [Link] file.
4. Connect to MongoDB
Create a file named [Link] and add the following code:
const { MongoClient } = require('mongodb');
Const
uri='mongodb+srv://<username>:<password>@[Link]
.net/test?retryWrites=true&w=majority';
const client = new MongoClient(uri);
async function run() {
try {
await [Link]();
const database = [Link]('sample_db');
const collection = [Link]('sample_collection');
const document = await [Link]({ name: 'John
Doe' });
[Link](document);
} finally {
await [Link]();
}
}
run().catch([Link]);
Replace <username> and <password> with your MongoDB
credentials. You can obtain your connection string from your
MongoDB Atlas dashboard.
[Link]
🚀 5. Run Your Application
Execute the following command to run your application:
bash
Copy
Edit
node [Link]
This will connect to your MongoDB database and log the document
matching the specified query.
🧪 6. Verify the Connection
Ensure your MongoDB server is running and accessible. If you're
using MongoDB Atlas, verify that your IP address is whitelisted and
that your credentials are correct.
how to add the MongoDB driver to your [Link] project:
1. Prerequisites:
[Link] and npm:
Ensure you have [Link] (version 12 or later) and npm (Node Package
Manager) installed.
MongoDB:
Have MongoDB installed and running. You can download it from the official
MongoDB website or use a cloud service like MongoDB Atlas.
2. Create a [Link] Project:
If you don't have an existing project, create a new directory and
initialize a [Link] project:
Code
mkdir my-mongodb-app
cd my-mongodb-app
npm init -y
3. Install the MongoDB Driver:
Use npm to install the official MongoDB [Link] driver:
Code
npm install mongodb
4. Connect to MongoDB:
Create a JavaScript file (e.g., [Link]) and use the following code
to establish a connection:
JavaScript
const { MongoClient } = require('mongodb');
async function main() {
const uri = "mongodb://localhost:27017"; // Replace
with your MongoDB connection string
const client = new MongoClient(uri);
try {
await [Link]();
[Link]("Connected successfully to server");
const db = [Link]("mydatabase"); // Replace with
your database name
const collection = [Link]("mycollection"); //
Replace with your collection name
// Perform database operations here
} catch (err) {
[Link]("Error connecting to MongoDB:", err);
} finally {
await [Link]();
}
}
main().catch([Link]);
5. Explanation:
require('mongodb'): Imports the MongoDB driver.
MongoClient: Creates a new MongoClient instance using the connection
string.
[Link](): Establishes a connection to the MongoDB server.
[Link](): Selects the database to use.
[Link](): Selects a collection within the database.
[Link](): Closes the connection when finished.
6. Important Considerations:
Connection String:
Replace "mongodb://localhost:27017" with your actual MongoDB
connection string, which may include a username, password, and database
name.
Database and Collection Names:
Update "mydatabase" and "mycollection" with the names of your
database and collection.
Error Handling:
Always include error handling to gracefully manage connection and query
issues.
Asynchronous Operations:
MongoDB operations are asynchronous, so use async/await or Promises
to handle them properly.
CRUD Operations:
Once connected, you can use methods
like insertOne(), find(), updateOne(), and deleteOne() to interact
with your data.
Connecting to MongoDB from [Link]
To connect MongoDB with [Link], you can use either the native
MongoDB [Link] driver or the Mongoose ODM (Object Data
Modeling) library.
Option 1: Using the Native MongoDB
Driver
1.
Install the MongoDB Driver:
npm install mongodb
Create a Connection File ([Link]):
const { MongoClient } = require('mongodb');
const uri = 'mongodb://localhost:27017'; // Replace with your
connection string
const client = new MongoClient(uri);
async function run() {
try {
await [Link]();
const database = [Link]('sample_mflix');
const movies = [Link]('movies');
const query = { title: 'Back to the Future' };
const movie = await [Link](query);
[Link](movie);
} finally {
await [Link]();
run().catch([Link]);
Run the Script:
node [Link]
This script connects to a local MongoDB instance, queries the movies collection in
the sample_mflix database, and logs the result.
🧩 Option 2: Using Mongoose
(Recommended for Schema-Based
Applications)
Install Mongoose:
npm install mongoose
onst mongoose = require('mongoose');
const uri = 'mongodb://localhost:27017/sharkinfo'; // Replace with your
database URI
[Link](uri, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => [Link]('MongoDB connected'))
.catch(err => [Link]('MongoDB connection error:', err));
Use the Connection in Your Application:
const express = require('express');
const app = express();
require('./db'); // Import the database connection
// Define your routes and models here
[Link](3000, () => {
[Link]('Server running on [Link]
});
Mongoose simplifies database operations by providing a schema-based solution to
model application data, including built-in type casting, validation, query building, and
more.
Understanding the Objects Used in the MongoDB
[Link] Driver
The MongoDB [Link] driver provides a set of structured objects to
facilitate interactions with a MongoDB database. These objects
represent various components and operations within the database.
Here's an overview of the key objects you'll encounter
. MongoClient
Purpose: Serves as the entry point to the MongoDB database.
Usage: Used to connect to a MongoDB server or cluster.
Example:
javascript
CopyEdit
const { MongoClient } = require('mongodb');
const client = new MongoClient('mongodb://localhost:27017');
await [Link]();
const db = [Link]('myDatabase');
2. Db
Purpose: Represents a specific database within the MongoDB server.
Usage: Provides methods to access collections and perform administrative
operations.
Example
javascript
const collection = [Link]('users');
3. Collection
· Purpose: Represents a collection within a database.
· · Usage: Provides methods for CRUD operations (Create, Read, Update, Delete)
on documents within the collection.
Example:
javascript
CopyEdit
const result = await [Link]({ name: 'Alice', age:
30 });
4. Cursor
Purpose: Represents the result set of a query.
Usage: Allows iteration over query results.
Example:
const cursor = [Link]({ age: { $gte: 18 } });
await [Link](doc => [Link](doc));