0% found this document useful (0 votes)
9 views19 pages

WT U5 Mongo Node 20 June 2022

MongoDB is a NoSQL document database that stores data in BSON format, which is a binary representation of JSON. It organizes documents into collections, requiring each document to have a unique _id field. The document database is commonly used with Node.js for creating modern applications, utilizing CRUD operations for data manipulation.

Uploaded by

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

WT U5 Mongo Node 20 June 2022

MongoDB is a NoSQL document database that stores data in BSON format, which is a binary representation of JSON. It organizes documents into collections, requiring each document to have a unique _id field. The document database is commonly used with Node.js for creating modern applications, utilizing CRUD operations for data manipulation.

Uploaded by

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

MongoDB with Node JS

How MongoDB Stores Data

MongoDB stores data in BSON documents. BSON is a binary representation of JSON


(JavaScript Object Notation) documents.

MongoDB stores groups of documents in collections. For those with a SQL


background, you can think of a collection as being roughly equivalent to a table.

Every document is required to have a field named _id. The value of _id must be unique
for each document in a collection, is immutable and can be of any type other than an
array. MongoDB will automatically create an index on _id. You can choose to make the
value of _id meaningful (rather than a somewhat random ObjectId) if you have a unique
value for each document that you'd like to be able to quickly search.
The sample_airbnb database contains one collection: listingsAndReviews. This collection contains documents about
Airbnb listings and their reviews.

Let's take a look at a document in the listingsAndReviews collection. Below is part


of an
Extended JSON representation of a BSON document:
Create One Document

Let's create a new Airbnb listing. Call Collection's insertOne(). insertOne() will insert a single document into the collection. The
only
required parameter is the new document (of type object) that will be inserted. If our new document does not contain the _id field,
the MongoDB driver will automatically create an _id for the document. Our function to create a new listing will look something
like the following:

async function createListing(client, newListing){


const result = await
client.db("sample_airbnb").collection("listingsAndReviews").ins
ertOne(newListing);
console.log(`New listing created with the following id:
${result.insertedId}`);
}

We can call this function by passing a connected MongoClient as well as an object that contains
information about a listing.
await createListing(client,
{
name: "Lovely Loft",
summary: "A charming loft in Paris",
bedrooms: 1,
bathrooms: 1
}
);

The output would be something like the following:

New listing created with the following id:


5d9ddadee415264e135ccec8
Create Multiple Documents

Instead, you can choose to call Collection 's insertMany() . insertMany() will insert an array of documents into your
collection.
One important option to note for insertMany() is ordered. If ordered is set to true, the documents will be inserted in the order
given in the array. If any of the inserts fail (for example, if you attempt to insert a document with an _id that is already being used by
another document in the collection), the remaining documents will not be inserted. If ordered is set to false, the documents may not
be inserted in the order given in the array. MongoDB will attempt to insert all of the documents in the given array—regardless of
whether any of the other inserts fail. By default, ordered is set to true.
To begin working with MongoDB from a Node.js script, you should understand how MongoDB stores
data as well as the basic methods you can use to query your data.
How MongoDB Stores Data MongoDB stores data as BSON documents. BSON is a binary
representation of JSON (JavaScript Object Notation).
Documents are similar in structure to JavaScript objects and store information in field-value pairs.
Every document is required to have an _id field. The value stored in _id must be unique for every
document in the collection.
Documents typically contain information about one object and any information that will be queried with
that object. Related documents are grouped together in collections. Related collections are stored
together in databases.
MongoDB is a flexible, general-purpose document database that is ideally
suited for modern applications.. Node.js is a JavaScript runtime that commonly
powers web servers. Developers can use these two pieces of technology,
along with MongoDB Atlas, a fully managed, multi-cloud database service, to
rapidly create modern applications.

CRUD Operations
The MongoDB Node.js driver provides a variety of
methods to help you query your data. These methods are
known as CRUD (create, read, update, and delete)
operations.
Create
Use insertOne() to create a new document. insertOne() has only one required
parameter: the document to insert. If the document does not include a field
named _id, the MongoDB Node.js driver will add one automatically.
To create multiple documents, use insertMany(). The only argument you are
required to pass to insertMany() is an array of documents to insert.
Both insertOne() and insertMany() allow you to pass optional settings. One
optional setting to note for insertMany() is the boolean ordered. If an insert fails
when ordered is to true, the remaining inserts will not be executed. If an insert
fails when ordered is to false, the remaining inserts will be executed. See
the official documentation for more information.
Read
To retrieve a single document from your database, use findOne(). findOne()
requires that you pass a query object. The query can contain zero to many
properties.
To retrieve multiple documents from your database, use find(). Like findOne(),
find() requires you to pass a query object that contains zero to many
properties. find() returns a cursor that you can use to iterate over the results.
Both findOne() and find() allow you to pass optional settings when you call
them. One handy option is projection, which allows you to explicitly exclude or
include the fields that are returned in the query.
Update
Use updateOne() when you want to update a single document. updateOne() has
two required parameters: a filter object that indicates which document should be
updated and an update object that indicates the update operations that should be
applied to the document.
To update multiple documents, you can use updateMany(). updateMany() has the
same required parameters as updateOne(): a filter object and an update object.
Both updateOne() and updateMany() allow you to pass optional settings to them
when you call them. upsert is one of the options you can pass. When upsert is set
to true, a new document will be created if no document matches the query. upsert
can be really helpful as it allows you to combine multiple operations into one:
checking to see if a document exists and then updating the document if it exists or
creating a new document if it does not.
Delete
To delete a single document, use deleteOne(). A filter object that indicates the document to
be deleted is the only required parameter.
Use deleteMany() when you want to delete multiple documents. Like deleteOne(), the only
required parameter is the filter object.
Both deleteOne() and deleteMany() allow you to pass optional settings as well. See
the official documentation for more information.
Now you know the basics of querying data stored in a MongoDB database from a Node.js
script.
Creating a Database
To create a database in MongoDB, start by creating a MongoClient object, then specify
a connection URL with the correct ip address and the name of the database you want
to create.
MongoDB will create the database if it does not exist, and make a connection to it.

Creating a Collection
To create a collection in MongoDB, use the createCollection() method:

Insert Into Collection


To insert a record, or document as it is called in MongoDB, into a collection, we use the insertOne() method.
A document in MongoDB is the same as a record in MySQL
The first parameter of the insertOne() method is an object containing the name(s) and value(s) of each field in the document you want to insert.
It also takes a callback function where you can work with any errors, or the result of the insertion:

Insert Multiple Documents


To insert multiple documents into a collection in MongoDB, we use the insertMany() method.
The first parameter of the insertMany() method is an array of objects, containing the data you want to insert.
It also takes a callback function where you can work with any errors, or the result of the insertion:
Find One
To select data from a collection in MongoDB, we can use the findOne() method.
The findOne() method returns the first occurrence in the selection.
The first parameter of the findOne() method is a query object. In this example we use an empty query object, which selects all documents in a collection
(but returns only the first document).

Find All
To select data from a table in MongoDB, we can also use the find() method.
The find() method returns all occurrences in the selection.
The first parameter of the find() method is a query object. In this example we use an empty query object, which selects all documents in the collection.
No parameters in the find() method gives you the same result as SELECT * in MySQL.

Find Some
The second parameter of the find() method is the projection object that describes which fields to include in the result.
This parameter is optional, and if omitted, all fields will be included in the result.
Node.js MongoDB Query

Filter the Result


When finding documents in a collection, you can filter the result by using a query object.
The first argument of the find() method is a query object, and is used to limit the search.

Filter With Regular Expressions


You can write regular expressions to find exactly what you are searching for.
Regular expressions can only be used to query strings.
To find only the documents where the "address" field starts with the letter "S", use the regular expression /^S/:

Sort the Result


Use the sort() method to sort the result in ascending or descending order.
The sort() method takes one parameter, an object defining the sorting order.

Sort Descending
Use the value -1 in the sort object to sort
descending.

{ name: 1 } // ascending
{ name: -1 } // descending
Delete Document
To delete a record, or document as it is called in MongoDB, we use the deleteOne() method.
The first parameter of the deleteOne() method is a query object defining which document to delete.
Note: If the query finds more than one document, only the first occurrence is deleted.

Delete Many
To delete more than one document, use the deleteMany() method.
The first parameter of the deleteMany() method is a query object defining which documents to delete.

Drop Collection
You can delete a table, or collection as it is called in MongoDB, by using the drop() method.
The drop() method takes a callback function containing the error object and the result parameter which returns true if the collection was dropped successfully,
otherwise it returns false.

db.dropCollection
You can also use the dropCollection() method to delete a table (collection).
The dropCollection() method takes two parameters: the name of the collection and a callback function.
Update Document
You can update a record, or document as it is called in MongoDB, by using the updateOne() method.
The first parameter of the updateOne() method is a query object defining which document to update.
Note: If the query finds more than one record, only the first occurrence is updated.
The second parameter is an object defining the new values of the document.

Update Only Specific Fields


When using the $set operator, only the specified fields are updated:

Update Many Documents


To update all documents that meets the criteria of the query, use the updateMany() method.

Limit the Result


To limit the result in MongoDB, we use the limit() method.
The limit() method takes one parameter, a number defining how many documents to return.

Join Collections
MongoDB is not a relational database, but you can perform a left outer join by using the $lookup stage.
The $lookup stage lets you specify which collection you want to join with the current collection, and which fields that should match.
What is Node.js?
Node.js is an open-source JavaScript runtime environment that allows
back-end developers to use JavaScript to create server-side applications
and APIs.

What is Node.js Used For?


Using Node.js allows your front-end (i.e. React, Vue.js, even jQuery) developers to use the
same programming language, JavaScript, as your backend developers. This allows for more
cross-functional and agile development. Node.js usage is widespread and ongoing, and I highly
recommend it for new development.
The Benefits of NoSQL
In contrast, NoSQL databases are great for situations where you need high performance, the ability to
scale horizontally, and are dealing with large amounts of unstructured data. NoSQL databases store
data in flexible formats—such as graphs, key/values, and documents—which can easily store a wide
variety of data. And, because the data is not relationally linked, a NoSQL database can be
significantly faster and easier to design, update, and scale.
Perhaps the most commonly used NoSQL database is MongoDB, an open-source document
database. In fact, the combination of MongoDB for the database, the Express framework for the back
end, React for the front end, and Node.js as the web server is so popular that it is known as the
MERN stack for web apps. For the purposes of this article, I’ll use MongoDB as an example of a
NoSQL database.

You might also like