How to Perform a findOne Operation in MongoDB using Node.js?

The findOne operation in MongoDB is used to get a single document from the collection if the given query matches the collection record. While using findOne, if more than one record is there with the exact same match, then it will return the very first one. We will use this operation if we need to fetch a specific record, like a user’s profile, any specific product detail, or any document that uniquely identifies an entity in your application.

Prerequisites:

Steps to Setup the Project

Step 1: Create a new directory for your project and navigate into it

mkdir myapp
cd myapp

Step 2: Initialize a new Node.js project

npm init -y

Step 3: Install the necessary packages/libraries in your project using the following commands.

npm install mongoose

Project Structure:

The updated dependencies in package.json file will look like:

"dependencies": {
"mongoose": "^8.4.0"
}

Connecting to MongoDB

Step 1: Importing the required dependencies

This line imports the MongoClient class from the mongodb package, which is used to setup a connection with the MongoDB database.

const { MongoClient } = require('mongodb');

Step 2: Defining the main async function

The main function is defined as an asynchronous function using the async keyword, we use the await keyword to handle the asynchronous operations.

async function main() {
// ...
}

Step 3: Connecting to the MongoDB database

  • Now here we define the mongoDB connection URI, which will specify the host and the port on which it will run, in our case it is the local host.
  • A new MongoClient instance is created using the provided URI and some additional options (useNewUrlParser and useUnifiedTopology).
  • The client.connect() method is called asynchronously using await keyword it will make sure that mongoDB database it connected.
  • If the connection is successful, we can see the message on the console. that “Connected to database” .
  • If an error occurs during the connection or operation, we will see that too in the terminal or the console.
  • Finally, we can close the connection using the client.close() method to release the resources.
const uri = 'YOUR_URI';
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });


try {
await client.connect();
console.log('Connected to database');
// ...
} catch (error) {
console.error('Error connecting to the database or performing the operation:', error);
} finally {
await client.close();
}

Step 5: Creating a new database and collection:

Here we are creating a new database it will be named “gfg” and in that database a new collected is created named “students”.

const database = client.db('gfg');
const collection = database.collection('students');

Step 6: Inserting sample data into the collection:

The insertMany method is used to insert multiple data at a time, here in the students collection three documents are inserted.

    await collection.insertMany([
{ name: "Alice", age: 25, city: "Los Angeles" },
{ name: "Bob", age: 30, city: "San Francisco" },
{ name: "Charlie", age: 35, city: "Seattle" }
]);

Step 7: Performing the findOne operation:

  • Now this is where the findOne operation working starts, we define a query object so that we can search for a document that contains the name equal to the “Alice”.
  • The findOne method is called on the collection, here we pass the query object, now here await keyword is used which means it will wait for the asynchronous operation to complete.
  • The result of the findOne operation, will be stored in the varibale with the name equal to the “Alice”.
  • And Finally we can see the output in the console or the Terminal.
const query = { name: "Alice" };
const result = await collection.findOne(query);
console.log('Found document:', result);

Example: Here in this example code, we will write the logic to connect to the mongodb database, then create the database and then create the collections inside that database, and inserting multiple data in the collections, and finally perform the findOne operation on that.

JavaScript
//index.js

const { MongoClient } = require('mongodb');

async function main() {
    const uri = 'YOUR_URI';
    const client = new MongoClient(uri,
        {
            useNewUrlParser: true,
            useUnifiedTopology: true
        });

    try {
        await client.connect();
        console.log('Connected to database');

        const database = client.db('gfg');
        const collection = database.collection('students');

        // Insert sample data
        await collection.insertMany([
            { name: "Alice", age: 25, city: "Los Angeles" },
            { name: "Bob", age: 30, city: "San Francisco" },
            { name: "Charlie", age: 35, city: "Seattle" }
        ]);

        // Perform findOne operation
        const query = { name: "Alice" };
        const result = await collection.findOne(query);
        console.log('Found document:', result);

    } catch (error) {
        console.error('Error connecting to the database or performing the operation:', error);
    } finally {
        await client.close();
    }
}

main();

Step to Run Application: Run the application using the following command from the root directory of the project

node .\index.js

After running the script, a new database named “gfg” and a new collection named “students” are created, and the three sample documents are inserted into the “students” collection.



Contact Us