WT U5 Mongo Node 20 June 2022
WT U5 Mongo Node 20 June 2022
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 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:
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
}
);
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:
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
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.
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.