MongoDB is a NoSQL (non-relational) document database. It is scalable and may be used to hold a variety of data types. MongoDB, unlike tables, organizes data into documents and collections, allowing users to store even unstructured data. You’ll need to simplify your development and management activities when using MongoDB. 

A MongoDB JavaScript (Node.js) connection will make the websites and applications user interactive, allow companies to use data through a MongoDB JavaScript (Node.js) connection, and manipulate data. In this article, you will get a brief introduction to the MongoDB database, JavaScript, and the steps to set up a MongoDB JavaScript (Node.js) connection.

What is MongoDB?

MongoDB is a well-known open-source document database built on the C++ programming language. MongoDB is a document-oriented database that uses JSON-like documents and a flexible schema to store information. This means that your schema easily evolves over time alongside your application. MongoDB allows variability in the number of fields, or the types of fields used to store values. JSON objects are similar to MongoDB documents, and may be easily stored without modification.

What is JavaScript?

JavaScript is a simple programming language that enables users to add advanced features and functionality to websites. It provides behavior to a webpage, and JavaScript is used by roughly 97% of all websites on the internet. On the client-side, websites use JavaScript and frequently use third-party libraries. For running JavaScript code on clients’ devices, all major web browsers include a JavaScript engine. The static webpage is transformed into an interactive webpage using JavaScript.

MongoDB JavaScript (Node.js) Configuration Steps

Step 1: Install Node.js and MongoDB JavaScript (Node.js) Driver

  • First, make sure you have a version of Node.js that is supported. Node 20.x or higher is required for the current version of the MongoDB JavaScript (Node.js) Driver. Node.js 23.11.0 is being used for these examples.
  • For additional information on which version of Node.js is required for each version of the MongoDB JavaScript (Node.js) Driver, see the MongoDB Compatibility documentation.
  • The MongoDB JavaScript (Node.js) Driver makes it simple to work with MongoDB databases from Node.js applications.
  • To connect to your database and run the queries discussed in this Quick Start series, you’ll need the MongoDB JavaScript (Node.js) Driver. If you don’t already have the MongoDB JavaScript (Node.js) Driver installed, use the following command to do so.

npm install mongodb

  • The MongoDB JavaScript (Node.js) Driver was installed with version 6.16.0 at the time of writing. The current MongoDB JavaScript (Node.js) Driver version number may be found by running npm search mongodb. See the official documentation for further information on the MongoDB JavaScript (Node.js) Driver and installation.
  • Also, install another library for environment variables. You’ll create a username and password for your cluster momentarily. We’ll use security best practices to inform the code with the username and password using environment variables. The dotenv library will accomplish that.
    npm install dotenv

Step 2: Create a Free Cluster and Get Your Cluster’s Connection Information

  • After that, you’ll require a MongoDB database. MongoDB Atlas, MongoDB’s fully-managed database-as-a-service, is the simplest way to get started with MongoDB.
  • To get started, go to MongoDB Atlas and establish a new cluster using the free tier. A cluster is a collection of computers where copies of your database are stored at a high level. Load the example data using the MongoDB Atlas interface into your tier once it’s been built. 
  • The next step is to get your cluster ready to connect. Navigate to your cluster in MongoDB Atlas and click CONNECT. The Cluster Connection Wizard will show on the screen.
  • If you haven’t already done so, the wizard will prompt you to add your current IP address to the IP Access List and create a MongoDB User. Make a note of the new MongoDB User’s Username and Password because you’ll need them later.
  • The wizard will then ask you to select a connection method. Connect Your Application is the option to choose. Select Node.js and 3.7 or later when the Wizard asks you to choose your MongoDB JavaScript (Node.js) Driver version. Copy the connection string that has been provided.

See the official documentation for further information on how to use the Connection Wizard and follow the procedures outlined above.

Step 3: Import MongoClient

  • MongoClient is an export from the MongoDB module that you’ll use to connect to a MongoDB database. You can connect to a cluster, access the database in that cluster, and end the connection to that cluster using a MongoClient instance.

const {MongoClient} = require(‘mongodb’);

  • We’ll also use the dotenv package to define environment variables for security best practices.
    require(‘dotenv’).config();

Step 4: Create Your Primary Function

Let’s make a main() asynchronous function that connects to our MongoDB cluster, calls methods that query our database, and then disconnects from your cluster.

async function main() {

// we’ll add code here soon

}

Inside main(), the first thing we need to do is construct a constant for our connection URI. The connection URI is the connection string you copied in the previous section and pasted into MongoDB Atlas. We’ll use variables for the username, password, and hostname that we’ll populate later with environment variables. They’re needed to connect.

/**

 * Connection URI. Update <your-cluster-url> to reflect your cluster.

 * See https://docs.mongodb.com/ecosystem/drivers/node/ for more details

 */

const username = process.env.DB_USERNAME;

const password = process.env.DB_PASSWORD;

const hostname = process.env.DB_HOSTNAME;

const uri = “mongodb+srv://${username}:${password}@${hostname}/sample_airbnb?retryWrites=true&w=majority”;

You may build a MongoClient instance now that you know the URL.

const client = new MongoClient(uri);

You’re ready to connect to the cluster with MongoClient. A promise will be returned by client.connect(). When you use client.connect(), you’ll use the await keyword to signify that you shouldn’t do anything else until that operation is finished.

await client.connect();

You’re now ready to work with the database. Let’s create a function that reports the existing database names. To increase the readability of your software, it’s often a good idea to put this logic in well-named functions. As you learn how to construct different types of queries, you’ll create new functions identical to the one you’re creating here throughout these steps. Let’s call a method listDatabases() for now.

await listDatabases(client);

To handle any unexpected failures, wrap your calls to functions that interface with the database in a try/catch statement.

try {

    await client.connect();

    await listDatabases(client);

} catch (e) {

    console.error(e);

}

You’ll finish the try/catch with a final statement to ensure that you close the connection to the cluster.

finally {

    await client.close();

}

You must call our main() function once it has been written. Let’s use the console to send the errors.

main().catch(console.error);

When it’s all put together, the main() function and the call to it should look like this.

async function main(){

/**

 * Connection URI. Update <username>, <password>, and <your-cluster-url> to reflect your cluster.

 * See https://docs.mongodb.com/ecosystem/drivers/node/ for more details

 */

const username = process.env.DB_USERNAME;

const password = process.env.DB_PASSWORD;

const hostname = process.env.DB_HOSTNAME;

const uri = `mongodb+srv://${username}:${password}@${hostname}/test?retryWrites=true&w=majority`;

const client = new MongoClient(uri);

    try {

        // Connect to the MongoDB cluster

        await client.connect();

        // Make the appropriate DB calls

        await  listDatabases(client);

    } catch (e) {

        console.error(e);

    } finally {

        await client.close();

    }

}

main().catch(console.error);

Also, don’t forget the lines covered earlier above the main function definition defining MongoClient and importing dotenv.

Step 5: List the Databases in Your Cluster

This function will get a list of your cluster’s databases and output the results to the console.

async function listDatabases(client){

    databasesList = await client.db().admin().listDatabases();

    console.log(“Databases:”);

    databasesList.databases.forEach(db => console.log(` – ${db.name}`));

};

You’ve been putting a lot of code in place. Save your changes and rename the file connection.js to reflect your changes. Visit the nodejs-quickstart GitHub repo to see a copy of the entire file.

Step 6: Implement Your Node.js Script

We need one more file before continuing. Create a new file called .env (a period, or dot, then env). Add three lines to the file to create environment variables. The place holders <username>, <password>, and <hostname> should be replaced with the username and password you created when configuring the cluster. Change the <hostname> placeholder to the hostname portion of the connection string provided by Atlas.

DB_USERNAME=<username>
DB_PASSWORD=<password>
DB_HOSTNAME=<hostname>

Now, it’s time to put your code to the test! Run the following command in your terminal to execute your script: 

node connection.js

What Are Some Other Ways to Connect to MongoDB?

Connect to a Replica Set

A MongoDB replica set deployment is a collection of linked instances that all hold the same data. Data redundancy and excellent data availability are provided by this combination of instances. MongoDB Atlas always uses replica sets, so your example code includes a connection string that connects appropriately to the replica set nodes. However, there are other ways of connecting using a different style of connection string.

To connect to a replica set deployment, use the connection string provided by the MongoDB Atlas UI. It begins with mongodb+srv://, which alerts the MongoDB Driver to identify the servers in the replica set deployment through TXT and SRV DNS records.

mongodb+srv://

By default, the MongoDB JavaScript (Node.js) Driver performs the following tasks while establishing a connection:

  • It uses the connection string to query DNS records for the replica set hosts.
  • When a replica set member’s address is found, it finds all other active members in the replica set by connecting to the first replica set member.
  • It dispatches operations to the appropriate member, such as writing against the primary.

Understanding MongoDB JavaScript (Node.js) CRUD Operations

1) Create

Create One Document 

Let’s start by making a brand-new Airbnb listing. You can achieve this by using the insertOne() command on a collection object. It inserts a single document into the collection with insertOne(). The new document (of type object) being inserted is the only required parameter. If your new document does not have a _id column, the MongoDB JavaScript (Node.js) Driver will construct one automatically before sending the object to the server.

The following function creates a new listing in the listingsAndReviews collection within the sample_airbnb database:

async function createListing(client, newListing){

    const listingsAndReviewsCollection = client.db(“sample_airbnb”).collection(“listingsAndReviews”);

    const result = await listingsAndReviewsCollection.insertOne(newListing);

    console.log(`New listing created with the following id: ${result.insertedId}`);

}

This function requires two parameters: the connected MongoClient and an object containing listing information.

await createListing(client,

        {

            name: “Lovely Loft”,

            summary: “A charming loft in Paris”,

            bedrooms: 1,

            bathrooms: 1

        }

    );

The following is an example of the output:

New listing created with the following id: 5d9ddadee415264e135ccec8

Since you didn’t include a field named _id in the document, the MongoDB JavaScript (Node.js) Driver added one automatically. The driver creates an _id value of type ObjectId whenever it is created automatically, which is a 12-byte value that is commonly represented as a 26-byte string. For example, ObjectId(“5d9ddadee415264e135ccec8”) is actually stored in the database using 12 bytes but represented here as a hexadecimal equivalent. Each document you create will have a different _id from the one indicated above. 

The _id field acts as a primary key. That means it should uniquely identify the object you’re inserting based on the domain of the data. MongoDB will automatically use an ObjectId data type if a value isn’t provided, but you may use any value of any data type (other than array) for _id. It always indexes because it’s the primary key, so it’s wise to use the value for easy and fast querying.

Create Multiple Documents 

You may want to insert multiple documents at once. You have the option of continually calling insertOne(), but it’s inefficient for adding multiple documents. Depending on how your code is designed, you may end up waiting for each insert operation to complete separately before moving on to the next, resulting in slow code. Each operation requires a network round-trip.

Instead, you can use the collection object’s insertMany() method. The insertMany() method will populate your collection with multiple documents by taking an array of objects as its first parameter.

There are two ways of using insertMany: ordered and unordered. If order is true, the documents will be placed in the array in the order specified. The remaining documents will not be inserted if any of the inserts fail (for example, if you try to insert a document with an _id that is already in use by another document in the collection).

If an order is false, the documents will not be inserted in the array’s specified order. The order doesn’t matter for retrieval purposes, but an unordered insert changes how errors are handled. MongoDB will attempt to insert all of the documents in the specified array even if one or more documents fail to insert. Ordered is set to true by default.

Let’s construct a function that will generate several Airbnb listings.

async function createMultipleListings(client, newListings){

    const collection = client.db(“sample_airbnb”).collection(“listingsAndReviews”);

    const result = await collection.insertMany(newListings);

    console.log(`${result.insertedCount} new listing(s) created with the following id(s):`);

    console.log(result.insertedIds);       

}

This function can be called by passing a connected MongoClient and an array of objects containing listing information.

await createMultipleListings(client, [

    {

        name: “Infinite Views”,

        summary: “Modern home with infinite views from the infinity pool”,

        property_type: “House”,

        bedrooms: 5,

        bathrooms: 4.5,

        beds: 5

    },

    {

        name: “Private room in London”,

        property_type: “Apartment”,

        bedrooms: 1,

        bathroom: 1

    },

    {

        name: “Beautiful Beach House”,

        summary: “Enjoy relaxed beach living in this house with a private beach”,

        bedrooms: 4,

        bathrooms: 2.5,

        beds: 7,

        last_review: new Date()

    }

]);

The following is an example of the output of calling createMultipleListings():

3 new listing(s) created with the following id(s):

  ‘0’: 5d9ddadee415264e135ccec9,

  ‘1’: 5d9ddadee415264e135cceca,

  ‘2’: 5d9ddadee415264e135ccecb 

}

When you used insertOne(), the MongoDB JavaScript (Node.js) Driver automatically built the _id field for you. When you called insertMany(), the MongoDB JavaScript (Node.js) Driver created the _id field for you again.

2) Update 

Update a Single Document 

Updating a single document uses the updateOne() method. The first parameter is the query that finds the document to be updated. If multiple documents match the query, only the first document will be updated.

The section parameter is an object containing one or more operators. An operator represents any action that should be taken on the document. For example, to set a value within the document, use the $set operator. Increment a value using the $inc operator. Push an element into an array using the $push operator. There are hundreds of operators and a summary of them is available in the MongoDB documentation.

Here is an example function that updates one of the documents inserted in the previous section.

async function updateListingByName(client, query, updateStatement){

    const collection = client.db(“sample_airbnb”).collection(“listingsAndReviews”);

    const result = await collection.updateOne(query, updateStatement);

    console.log(`${result.matchedCount} document matched, and ${result.modifiedCount} document updated`);   

}

Call the function using this statement:

await updateListingByName(client, 

    { name: “Infinite Views” }, 

    {

        $set: { bedrooms: 7, updatedOn: new Date() },

        $inc: { beds: 1 },

        $push: { ammenities: { $each: [ “Wifi”, “Pool” ] } 

    }

);

The output of running the command above is as follows.

1 document matched, and 1 document updated.

The example finds the document with a name field “Infinite Views.” It then sets the bedrooms field to 7 (changed from 5), adds a new field called updatedOn with the current date and time, increases the beds field by 1 (setting it to 5 from 4), and creates a new field amenities of type array and adds the arrays elements “Wifi” and “Pool.”

Upsert is one of the parameters you can supply to updateOne(). Upsert is a useful tool that allows you to update or insert a document if one already exists.

Let’s imagine you wanted to make sure an Airbnb listing with a specific name had a specific amount of bedrooms and bathrooms. You’d have to use findOne() first to see if the document existed if you didn’t use upsert.

If the document already existed, you’d update it with updateOne(). You’d use insertOne() to create the document if it didn’t already exist. You can bundle all of those capabilities into one command using upsert.

With one crucial modification, the function to upsert a listing with a certain name can be nearly identical to the function defined above: In the options argument for updateOne(), you’ll pass {upsert: true}.

async function upsertListingByName(client, nameOfListing, updatedListing) {

    const result = await client.db(“sample_airbnb”).collection(“listingsAndReviews”)

                        .updateOne({ name: nameOfListing }, 

                                   { $set: updatedListing }, 

                                   { upsert: true });

    console.log(`${result.matchedCount} document(s) matched the query criteria.`);

    if (result.upsertedCount > 0) {

        console.log(`One document was inserted with the id ${result.upsertedId._id}`);

    } else {

        console.log(`${result.modifiedCount} document(s) was/were updated.`);

    }

}

Let’s imagine you’re not sure if a listing called “Cozy Cottage” exists in the database or, if it does, if it contains outdated information. In any case, you want to make sure that the information in the collection is current. With a connected MongoClient, the name of the listing, and an object containing the up-to-date data that should be in the listing, you may run upsertListingByName().

await upsertListingByName(client, “Cozy Cottage”, { name: “Cozy Cottage”, bedrooms: 2, bathrooms: 1 });

If the document had never been before, the function’s output would look something like this:

0 document(s) matched the query criteria.

One document was inserted with the id 5db9d9286c503eb624d036a1

In the listingsAndReviews collection, you’ve included a new document:

    _id: 5db9d9286c503eb624d036a1,

    name: ‘Cozy Cottage’,

    bathrooms: 1,

    bedrooms: 2 

}

You can use upsertListingByName() again if we find out more about the “Cozy Cottage” listing.

await upsertListingByName(client, “Cozy Cottage”, { beds: 2 });

And you’d get the following result.

1 document(s) matched the query criteria.

1 document(s) was/were updated.

A new field called “beds” has been added to the paper.

    _id: 5db9d9286c503eb624d036a1,

    name: ‘Cozy Cottage’,

    bathrooms: 1,

    bedrooms: 2,

    beds: 2 

}

Update Multiple Documents 

You might want to change multiple documents at the same time. In this instance, you can use the updateMany() method of a collection. The updateMany() method, like updateOne(), expects a filter of type object and an update of type object. You can also choose to include type object options.

Unlike updateOne(), which updates the first document that satisfies the query and returns, the updateMany() method will update every document that matches the query. It’s a bulk update statement that is run entirely on the server (i.e., no documents are returned to the client before updated), which avoids race conditions and allows execution to happen rapidly without network overhead.

Always consider how your bulk updates will impact performance on the server. If you update every document (or a significant number of documents), the database must find the documents to update and update them, using a database cache that might be required for other production workloads.

3) Delete

Delete Single Document 

Let’s delete a single Airbnb listing from the listingsAndReviews collection.

You can delete a single document by using the deleteOne() method in the collection. Only one parameter is required for deleteOne(): a query passed as an object. The query is used to find the document that needs to be deleted. The query is the same as the query parameter you used with findOne() and the query parameter you used in updateOne().

You can search for all documents in the collection by including zero properties in the query object, or you can refine your search by including one or more properties.

Optionally, deleteOne() has an options parameter. For additional information on these choices, see the deleteOne() documentation.

deleteOne() removes the first document that matches the specified query. Only one document will be deleted if more than one document matches the query. 

Assume you wish to remove an Airbnb listing with a specific name. The name of the listing will be included in the query parameter. You can write a function to remove a listing with a specific name from the database.

async function deleteListingByName(client, nameOfListing) {

    const collection = client.db(“sample_airbnb”).collection(“listingsAndReviews”);

    const result = await collection

            .deleteOne({ name: nameOfListing });

    console.log(`${result.deletedCount} document(s) was/were deleted.`);

}

Let’s imagine you wish to remove the “Cozy Cottage” Airbnb listing you made earlier in this section. By giving a connected MongoClient and the name “Cozy Cottage,” you can call deleteListingsByName().

await deleteListingByName(client, “Cozy Cottage”);

The output of running the command above is as follows.

1 document(s) was/were deleted.

Delete Multiple Documents 

You might want to remove multiple documents at the same time. In this scenario, you can utilize the deleteMany() method of collection. deleteMany(), like deleteOne(), requires a query object to be passed. You can also choose to include type object options.

Assume you want to get rid of documents that haven’t been updated in a while. With a query that searches for documents scraped before a certain date, you may run deleteMany(). The following is an example of the function.

async function deleteListingsScrapedBeforeDate(client, date) {

    const collection = client.db(“sample_airbnb”).collection(“listingsAndReviews”);

    const result = await collection

        .deleteMany({ “last_scraped”: { $lt: date } });

    console.log(`${result.deletedCount} document(s) was/were deleted.`);

}

With a connected MongoClient and a Date object instance that represents February 15, you can execute deleteListingsScrapedBeforeDate() to delete listings scraped prior to February 15, 2019.

await deleteListingsScrapedBeforeDate(client, new Date(“2019-02-15”));

When you run the command above, you’ll get the following output.

606 document(s) was/were deleted.

Our collection now only contains documents that have been scrapped recently.

4) Read

Read Single Document 

Let’s start by searching the listingsAndReviews collection for an Airbnb listing by name.

You can use the collection’s findOne() method to look for a document. The first document that matches the supplied query will be returned by findOne(). Only one document will be returned, even if more than one document fits the query.

There is only one needed parameter for findOne(): a query object. You may include zero or more properties in the query object to find a document in the collection. An empty query object will query all documents in a collection without restricting your results in any manner. Remember that a query returns all documents that satisfy its requirements. Providing no properties in a query object provides no requirements. All documents match a query object with no requirements.

You’ll include the name field in the query object we send to findOne() since you want to find an Airbnb listing with a certain name:

findOne({ name: nameOfListing })

The following is an example of a function to find a listing by querying the name field:

async function findOneListingByName(client, nameOfListing) {

    const collection = client.db(“sample_airbnb”).collection(“listingsAndReviews”);

    const result = await collection.findOne({ name: nameOfListing });

    if (result) {

        console.log(`Found a listing in the collection with the name ‘${nameOfListing}’:`);

        console.log(result);

    } else {

        console.log(`No listings found with the name ‘${nameOfListing}’`);

    }

}

This function can be called by giving a connected MongoClient and the name of the listing you want to find. Let’s look for the “Infinite Views” listing you made earlier in this part.

await findOneListingByName(client, “Infinite Views”);

The final product should look something like this:

Found a listing in the collection with the name ‘Infinite Views’:

  _id: ObjectId(“5da9b5983e104518671ae128”),

  name: ‘Infinite Views’,

  summary: ‘Modern home with infinite views from the infinity pool’,

  property_type: ‘House’,

  bedrooms: 7,

  bathrooms: 4.5,

  beds: 6,

  ammenities: [ “Wifi”, “Pool” ],

  updatedOn: Date(“2025-06-17”) 

}

It’s important to note that the _id and updatedOn values of the document in your database will differ from the example output.

Read Multiple Documents 

Let’s look at how to query for numerous documents at once now that you know how to query for a single item. You can accomplish so by querying the collection using the find() method.

The query object is the initial parameter for find(), just like it is for findOne(). In the query object, you can include zero to many properties.

Let’s say you want to find all Airbnb listings with at least two bedrooms and two bathrooms. Here is sample code for running that query:

client.db(“sample_airbnb”).collection(“listingsAndReviews”).find(

        {

            bedrooms: { $gte: 2 },

            bathrooms: { $gte: 2 }

        }

    );

As you can see, your query object has two properties: one for bedrooms and one for bathrooms. The $gte comparison query operator can be used to find documents with bedrooms greater than or equal to a certain number (two, in our example).

Additional properties act the same by adding more query predicates to your query. Other comparison query operators are available in MongoDB and can be used in your queries. 

The findOne() method we called earlier always returns an object. That’s because it’s a special case method that calls find() under the hood. The find() method returns a cursor. A cursor is an object that keeps track of which document you’re traversing in a query’s result set.

When a cursor is created, it sits unexecuted in memory on the client side. That means the server is not notified of the query. The cursor has several important methods that we’ll cover shortly for iterating through a result set, and using any of those methods will send the query to the server for execution, thus activating the cursor.

Before the cursor executes, there are helper functions that help modify the cursor. Let’s imagine you want to order results so that documents with the most recent reviews appear first.

The cursor has a sort() function that tells MongoDB to pre-sort the result set before sending it to the client. The parameter for sort is an object. The object must be in the format of <fieldName>: <0|1>. For example, sorting on the last_review field ascending uses this sort object: { last_review: 1 }. You may arrange the results in descending order by supplying -1 to sort(), which returns the listings with the most recent reviews first. 

The existing query may now be updated to look like this.

const cursor = client.db(“sample_airbnb”).collection(“listingsAndReviews”).find(

                        {

                            bedrooms: { $gte: minimumNumberOfBedrooms },

                            bathrooms: { $gte: minimumNumberOfBathrooms }

                        }

                    ).sort({ last_review: -1 });

Remember, the cursor hasn’t been executed on the server yet.

There are 192 documents in the library that match the above query. Let’s imagine you don’t want the script to process that many results. Rather, you’d like to confine your findings to a smaller number of documents.

You can use limit after the sort() method to specify the maximum number of documents returned by the server. The limit() modifier, as the name says, sets the cursor’s limit. You can now modify the query so that it only returns a set number of results.

const cursor = client.db(“sample_airbnb”).collection(“listingsAndReviews”).find(

                        {

                            bedrooms: { $gte: minimumNumberOfBedrooms },

                            bathrooms: { $gte: minimumNumberOfBathrooms }

                        }

                    ).sort({ last_review: -1 })

                    .limit(maximumNumberOfResults);

The cursor still hasn’t been executed on the server. For that to happen, the application must use the cursor to retrieve a document.

There are several ways to use cursors to retrieve documents. A common way is iterating over the cursor to get each result one at a time. Iterating a cursor in this way is generally a best practice. It prevents loading unnecessary or unused documents into client-side memory, and allows the client to operate without waiting for large result sets to traverse the network. However, for easy development, you may use the cursor’s toArray() method to retrieve all of the results in an array. Here is an example that executes the cursor server-side, and retrieves all results using the toArray() method:

const cursor = client.db(“sample_airbnb”).collection(“listingsAndReviews”).find(

                        {

                            bedrooms: { $gte: minimumNumberOfBedrooms },

                            bathrooms: { $gte: minimumNumberOfBathrooms }

                        }

                    ).sort({ last_review: -1 })

                    .limit(maximumNumberOfResults);

const results = await cursor.toArray();

Let’s wrap the query in an asynchronous function and add functionality to print the results.

async function findListingsWithMinimumBedroomsBathroomsAndMostRecentReviews(client, {

    minimumNumberOfBedrooms = 0,

    minimumNumberOfBathrooms = 0,

    maximumNumberOfResults = Number.MAX_SAFE_INTEGER

} = {}) {

    const cursor = client.db(“sample_airbnb”).collection(“listingsAndReviews”).find(

                            {

                                bedrooms: { $gte: minimumNumberOfBedrooms },

                                bathrooms: { $gte: minimumNumberOfBathrooms }

                            }

                            ).sort({ last_review: -1 })

                            .limit(maximumNumberOfResults);

    const results = await cursor.toArray();

    if (results.length > 0) {

        console.log(`Found listing(s) with at least ${minimumNumberOfBedrooms} bedrooms and ${minimumNumberOfBathrooms} bathrooms:`);

        results.forEach((result, i) => {

            date = new Date(result.last_review).toDateString();

            console.log();

            console.log(`${i + 1}. name: ${result.name}`);

            console.log(`   _id: ${result._id}`);

            console.log(`   bedrooms: ${result.bedrooms}`);

            console.log(`   bathrooms: ${result.bathrooms}`);

            console.log(`   most recent review date: ${new Date(result.last_review).toDateString()}`);

        });

    } else {

        console.log(`No listings found with at least ${minimumNumberOfBedrooms} bedrooms and ${minimumNumberOfBathrooms} bathrooms`);

    }

}

The function requires a connected MongoClient object, which is used to query the listingsAndReviews database. There are also three optional parameters that modify the query predicate passed to the find() method.

Here is an example function call:

await findListingsWithMinimumBedroomsBathroomsAndMostRecentReviews(client, {

    minimumNumberOfBedrooms: 4,

    minimumNumberOfBathrooms: 2,

    maximumNumberOfResults: 5

});

If you’ve followed the instructions in the previous section, the result should be something like this:

Found listing(s) with at least 4 bedrooms and 2 bathrooms:

1. name: Beautiful Beach House

    _id: 5db6ed14f2e0a60683d8fe44

    bedrooms: 4

    bathrooms: 2.5

    most recent review date: Mon Oct 28 2019

2. name: Spectacular Modern Uptown Duplex

    _id: 582364

    bedrooms: 4

    bathrooms: 2.5

    most recent review date: Wed Mar 06 2019

3. name: Grace 1 – Habitat Apartments

    _id: 29407312

    bedrooms: 4

    bathrooms: 2.0

    most recent review date: Tue Mar 05 2019

4. name: 6 bd country living near beach

    _id: 2741869

    bedrooms: 6

    bathrooms: 3.0

    most recent review date: Mon Mar 04 2019

5. name: Awesome 2-storey home Bronte Beach next to Bondi!

    _id: 20206764

    bedrooms: 4

    bathrooms: 2.0

    most recent review date: Sun Mar 03 2019

What Are MongoDB JavaScript (Node.js) Aggregation Operations?

Aggregation is used for obtaining reduced and summarised results. It’s how we answer questions like, “How many bedrooms exist across all listings?” or “What is the average ratio between bedrooms and bathrooms?”

Aggregations are run using the MongoDB aggregate pipeline. A pipeline is similar to a Linux pipe, where one command executes and its output is passed to another program. Aggregation in MongoDB works the same way.

A pipeline is built with one or more stages, each of which performs a different action on your data. For example, the $match stage works identically to a find statement, where its input may be all documents in a collection, and its output is a subset of those documents based on the filter provided to $match. The $group statement combines data together across multiple documents to create things like counts and averages.

There are too many aggregation stages to cover right now. However, the MongoDB documentation provides an extensive list of stages.

Conclusion

You’ve learned the core principles for using the MongoDB Javascript (Node.js) Connector. Using the database is simple, but mastering it requires more learning. For example, we only briefly touched on CRUD operations. Indexes, too, are a complex and incredibly useful topic to understand. And manual setup of any database, including MongoDB, can be challenging for a beginner. Hevo and MongoDB can help!

MongoDB offers a cloud-native document database-as-a-service called MongoDB Atlas. Starting a new cluster is simple, and free! However, more complex production environments require technical acumen to understand some code-heavy concepts. The data warehouse-as-a-service information from Hevo Data can help.

Sign up for a 14-day free trial and simplify your data integration process. Check out the pricing details to understand which plan fulfills all your business needs.

Share your learning experiences in the comments section below!

Share your experience of learning about! Let us know in the comments section below!

FAQ

How do you connect MongoDB with JavaScript?

You can connect MongoDB with JavaScript using the MongoDB Node.js driver. Install the driver using npm (npm install mongodb), then use the MongoClient class from the driver to connect to your MongoDB instance.

How do you insert a document into MongoDB using JavaScript?

After connecting to MongoDB, you can insert a document into a collection using the insertOne method. Here’s an example:
const db = client.db("myDatabase");
const collection = db.collection("myCollection");
async function insertDocument() {
const doc = { name: "John Doe", age: 25 };
await collection.insertOne(doc);
console.log("Document inserted");
}
insertDocument();

How do you query MongoDB using JavaScript?

You can query MongoDB using the find method after establishing a connection. For example, to find all documents where age is greater than 20:
async function queryDocuments() {
const result = await collection.find({ age: { $gt: 20 } }).toArray();
console.log(result);
}
queryDocuments();

Highly skilled background in computer programming, infrastructure management, project planning, and team development. Particularly interested in dev-ops and distributed computing. Industry Focuses: Go, MongoDB, MySQL, PL/SQL, RabbitMQ, C#, C/++, Javascript, Debian/Ubuntu, Red Hat (RHEL), LAMP, MVC, CakePHP, Oracle, Perl