Learning MongoDB

0% completed

Previous
Next
Querying MongoDB using NodeJs

Querying MongoDB from a NodeJS application allows developers to interact with their database efficiently. Using the MongoDB NodeJS driver, you can perform various read operations to fetch data based on specific criteria. This lesson will cover how to execute different types of queries, including finding documents, using query operators, and sorting and limiting results.

Inserting Data for Query Examples

Before we start querying, let's insert some sample data into our collection.

const { MongoClient } = require('mongodb'); async function insertData() { const uri = "mongodb://localhost:27017"; // Connection URI for MongoDB const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true }); // Create a new MongoClient try { await client.connect(); // Connect the client to the server const database = client.db('testDB'); // Specify the database to use const collection = database.collection('testCollection'); // Specify the collection to use // Insert multiple documents into the collection const docs = [ { name: "Alice", age: 30, profession: "Engineer" }, { name: "Bob", age: 25, profession: "Designer" }, { name: "Charlie", age: 35, profession: "Teacher" }, { name: "David", age: 40, profession: "Engineer" }, { name: "Eve", age: 22, profession: "Artist" } ]; const result = await collection.insertMany(docs); // Insert documents console.log(`${result.insertedCount} documents were inserted.`); // Output the number of inserted documents } finally { await client.close(); // Ensure the client will close when you finish/error } } insertData().catch(console.error); // Run the function and catch any errors

Explanation:

  • Connect to MongoDB: Connect to the MongoDB server using the MongoClient.
  • Specify Database and Collection: Define the database (testDB) and collection (testCollection) to use.
  • Insert Documents: Insert multiple documents into the collection.
  • Close Connection: Ensure the MongoClient is closed after the operation.

Basic Queries

Find One Document

The findOne method is used to find a single document that matches a specified query.

Example:

async function findOneExample() { const uri = "mongodb://localhost:27017"; // Connection URI for MongoDB const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true }); // Create a new MongoClient try { await client.connect(); // Connect the client to the server const database = client.db('testDB'); // Specify the database to use const collection = database.collection('testCollection'); // Specify the collection to use // Find one document matching the query const query = { name: "Alice" }; const result = await collection.findOne(query); // Execute the query console.log(result); // Output the result } finally { await client.close(); // Ensure the client will close when you finish/error } } findOneExample().catch(console.error); // Run the function and catch any errors

Explanation:

  • Find One Document: The findOne method is used to find a single document that matches the query { name: "Alice" }.

Finding Multiple Documents

Find All Documents

The find method is used to find multiple documents that match a specified query.

Example:

async function findAllExample() { const uri = "mongodb://localhost:27017"; // Connection URI for MongoDB const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true }); // Create a new MongoClient try { await client.connect(); // Connect the client to the server const database = client.db('testDB'); // Specify the database to use const collection = database.collection('testCollection'); // Specify the collection to use // Find all documents matching the query const cursor = collection.find({}); // Execute the find query const results = await cursor.toArray(); // Convert the cursor to an array console.log(results); // Output the results } finally { await client.close(); // Ensure the client will close when you finish/error } } findAllExample().catch(console.error); // Run the function and catch any errors

Explanation:

  • Find All Documents: The find method with an empty query {} retrieves all documents in the collection.
  • Convert Cursor to Array: The toArray method converts the cursor to an array of documents.

Using Query Operators

MongoDB provides various query operators to filter documents based on specific criteria.

Example: Using $gt and $lt Operators

Example:

async function queryOperatorsExample() { const uri = "mongodb://localhost:27017"; // Connection URI for MongoDB const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true }); // Create a new MongoClient try { await client.connect(); // Connect the client to the server const database = client.db('testDB'); // Specify the database to use const collection = database.collection('testCollection'); // Specify the collection to use // Find documents with age greater than 25 and less than 35 const query = { age: { $gt: 25, $lt: 35 } }; // Define the query with $gt and $lt operators const cursor = collection.find(query); // Execute the find query const results = await cursor.toArray(); // Convert the cursor to an array console.log(results); // Output the results } finally { await client.close(); // Ensure the client will close when you finish/error } } queryOperatorsExample().catch(console.error); // Run the function and catch any errors

Explanation:

  • Use Query Operators: The query { age: { $gt: 25, $lt: 35 } } uses the $gt (greater than) and $lt (less than) operators to filter documents where the age field is between 25 and 35.

Sorting and Limiting Results

Sort Results

The sort method is used to sort documents based on specified fields.

Example:

async function sortExample() { const uri = "mongodb://localhost:27017"; // Connection URI for MongoDB const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true }); // Create a new MongoClient try { await client.connect(); // Connect the client to the server const database = client.db('testDB'); // Specify the database to use const collection = database.collection('testCollection'); // Specify the collection to use // Find all documents and sort by age in descending order const cursor = collection.find({}).sort({ age: -1 }); // Execute the find and sort query const results = await cursor.toArray(); // Convert the cursor to an array console.log(results); // Output the results } finally { await client.close(); // Ensure the client will close when you finish/error } } sortExample().catch(console.error); // Run the function and catch any errors

Explanation:

  • Sort Results: The sort method sorts the documents by the age field in descending order (-1).

Limit Results

The limit method is used to limit the number of documents returned by a query.

Example:

async function limitExample() { const uri = "mongodb://localhost:27017"; // Connection URI for MongoDB const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true }); // Create a new MongoClient try { await client.connect(); // Connect the client to the server const database = client.db('testDB'); // Specify the database to use const collection = database.collection('testCollection'); // Specify the collection to use // Find all documents and limit the results to 2 const cursor = collection.find({}).limit(2); // Execute the find and limit query const results = await cursor.toArray(); // Convert the cursor to an array console.log(results); // Output the results } finally { await client.close(); // Ensure the client will close when you finish/error } } limitExample().catch(console.error); // Run the function and catch any errors

Explanation:

  • Limit Results: The limit method restricts the number of documents returned by the query to 2.

Combining Sort and Limit

You can combine sort and limit methods to control the order and number of documents returned.

Example:

async function sortAndLimitExample() { const uri = "mongodb://localhost:27017"; // Connection URI for MongoDB const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true }); // Create a new MongoClient ```javascript async function sortAndLimitExample() { const uri = "mongodb://localhost:27017"; // Connection URI for MongoDB const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true }); // Create a new MongoClient try { await client.connect(); // Connect the client to the server const database = client.db('testDB'); // Specify the database to use const collection = database.collection('testCollection'); // Specify the collection to use // Find all documents, sort by age in ascending order, and limit the results to 2 const cursor = collection.find({}).sort({ age: 1 }).limit(2); // Execute the find, sort, and limit query const results = await cursor.toArray(); // Convert the cursor to an array console.log(results); // Output the results } finally { await client.close(); // Ensure the client will close when you finish/error } } sortAndLimitExample().catch(console.error); // Run the function and catch any errors

Explanation:

  • Combine Sort and Limit: This example sorts the documents by the age field in ascending order (1) and limits the results to 2.

Querying MongoDB using NodeJS involves performing various read operations to fetch data from the database. By using the MongoDB NodeJS driver, you can execute queries to find documents, apply query operators, and control the results with sorting and limiting.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next