In the first post in this series, I walked you through how to connect to a MongoDB database from a Node.js script, retrieve a list of databases, and print the results to your console. If you haven’t read that post yet, I recommend you do so and then return here.
This post uses MongoDB 4.0, MongoDB Node.js Driver 3.3.2, and Node.js 10.16.3.
Click here to see a newer version of this post that uses MongoDB 4.4, MongoDB Node.js Driver 3.6.4, and Node.js 14.15.4.
Now that we have connected to a database, let’s kick things off with the CRUD (create, read, update, and delete) operations.
If you prefer video over text, I’ve got you covered. Check out the video in the section below. :-)
Get started with an M0 cluster on Atlas today. It’s free forever, and it’s the easiest way to try out the steps in this blog series.
Here is a summary of what we’ll cover in this post:
I created the video below for those who prefer to learn by video instead of text. You might also find this video helpful if you get stuck while trying the steps in the text-based instructions below.
Here is a summary of what the video covers:
insertOne()
and insertMany()
(11:01)findOne()
and find()
(20:04)updateOne()
with and without upsert
as well as updateMany()
(31:13)deleteOne()
and deleteMany()
(46:07)Note: In the video, I type main().catch(console.err);
, which is incorrect. Instead, I should have typed main().catch(console.error);
.
Below are the links I mentioned in the video.
Before we go any further, let’s take a moment to understand how data is stored in MongoDB.
MongoDB stores data in BSON documents. BSON is a binary representation of JSON (JavaScript Object Notation) documents. When you read MongoDB documentation, you’ll frequently see the term “document,” but you can think of a document as simply a JavaScript object. For those coming from the SQL world, you can think of a document as being roughly equivalent to a row.
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.
In this blog series, we’ll use the sample Airbnb listings dataset. The sample_airbnb
database contains one collection: listingsAndReviews
. This collection contains documents about Airbnb listings and their reviews.
#node.js #node