MongoDB Query

A query in MongoDB is a request to retrieve specific data from a collection based on conditions. MongoDB queries are highly flexible and can filter, sort, limit and project data efficiently.

What Is a MongoDB Query?

A MongoDB query retrieves documents from a collection based on specific conditions. You can:

  1. Filter Documents: Use query operators like $eq, $gt, and $lt to define conditions.
  2. Sort Results: Arrange data in ascending or descending order.
  3. Limit and Skip Results: Fetch only the required number of documents or skip initial results.
  4. Use Logical Operators: Combine multiple conditions using $and, $or etc.

Key Features of MongoDB Queries

  • Rich Query Operators: MongoDB offers advanced operators for conditions and filters.
  • Flexible Syntax: Queries support dynamic and complex conditions.
  • Schema-Less: You can query data without worrying about fixed schemas.

Prerequisites

  1. MongoDB Installed: Download MongoDB from mongodb.com.
  2. Node.js Installed: Download and install Node.js from nodejs.org.
  3. MongoDB Shell or Compass: Use either for database management.

Basic MongoDB Query Syntax

The general syntax for a query is:

db.collectionName.find(query, projection);
  • query: Specifies the condition to filter documents (optional).
  • projection: Specifies fields to include or exclude (optional).

Method 1: Querying in MongoDB Shell

Step 1: Open the MongoDB Shell

Run the following command:

mongosh

Step 2: Switch to a Database

Select the database you want to query:

use myDatabase

Step 3: Query All Documents

Fetch all documents from the users collection:

db.users.find()

Step 4: Query Specific Documents

Filter documents using conditions:

db.users.find({ age: { $gt: 25 } });
  • $gt: Greater than operator.
  • Result: Retrieves all documents where the age field is greater than 25.

Step 5: Use Projections

Return specific fields in the results:

db.users.find({ age: { $gt: 25 } }, { name: 1, age: 1, _id: 0 });
  • { name: 1, age: 1, _id: 0 }: Includes name and age fields while excluding _id.

Method 2: Querying in Node.js

Step 1: Install MongoDB Driver

Install the MongoDB driver using npm:

npm install mongodb

Step 2: Perform Queries in Node.js

Create a file named app.js and write the following code:

Query All Documents

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

// Connection URL
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url);

// Database Name
const dbName = 'myDatabase';

async function main() {
try {
// Connect to MongoDB
await client.connect();
console.log('Connected successfully to MongoDB');

// Select the database and collection
const db = client.db(dbName);
const collection = db.collection('users');

// Query all documents
const users = await collection.find().toArray();
console.log('All users:', users);
} catch (err) {
console.error('Error querying documents:', err);
} finally {
// Close the connection
await client.close();
}
}

main();

Query Specific Documents

async function querySpecificUsers() {
try {
await client.connect();
const db = client.db(dbName);
const collection = db.collection('users');

// Find users older than 25
const users = await collection.find({ age: { $gt: 25 } }).toArray();
console.log('Users older than 25:', users);
} catch (err) {
console.error('Error querying documents:', err);
} finally {
await client.close();
}
}

querySpecificUsers();

Advanced Querying

1. Combine Conditions

Use logical operators like $and $or and $not:

Example: Combine $and and $or

const users = await collection.find({
$and: [
{ age: { $gt: 25 } },
{ $or: [{ city: 'New York' }, { city: 'London' }] }
]
}).toArray();
console.log('Filtered users:', users);

2. Sort, Limit and Skip

Sort Results

const users = await collection.find().sort({ age: -1 }).toArray(); // Sort by age descending
console.log('Sorted users:', users);

Limit Results

const users = await collection.find().limit(5).toArray(); // Limit to 5 documents
console.log('Limited users:', users);

Skip Results

const users = await collection.find().skip(5).limit(5).toArray(); // Skip first 5 and fetch next 5
console.log('Paginated users:', users);

Querying in MongoDB Compass

  1. Open MongoDB Compass and connect to your server.
  2. Select the database and collection.
  3. Use the “Filter” box to write queries, e.g., { age: { $gt: 25 } }.
  4. Use the “Options” panel to sort and limit results.

Real-World Use Case

Imagine building a product catalog where users can search for products based on price, category, and ratings.

Example: Querying Products

async function queryProducts() {
const db = client.db('ecommerce');
const collection = db.collection('products');

const products = await collection.find({
$and: [
{ price: { $lt: 500 } }, // Price less than 500
{ category: 'Electronics' }
]
}).sort({ rating: -1 }).toArray(); // Sort by rating descending
console.log('Filtered products:', products);
}

queryProducts();

Leave a Comment

BoxofLearn