Consider this Express route that queries a MongoDB collection for users with age greater than 25:
app.get('/users', async (req, res) => {
const users = await User.find({ age: { $gt: 25 } });
res.json(users);
});What will the response contain?
app.get('/users', async (req, res) => { const users = await User.find({ age: { $gt: 25 } }); res.json(users); });
Think about what the MongoDB $gt operator does in a query.
The $gt operator selects documents where the value of the field is greater than the specified value. Here, it returns all users with age > 25 as an array.
You want to find all products with price less than 100 and category 'books'. Which query is correct?
const products = await Product.find( /* your query here */ );
Remember how to write multiple conditions in a MongoDB query object.
MongoDB queries use an object with key-value pairs for each condition. The correct syntax is { price: { $lt: 100 }, category: 'books' }.
Given this code:
app.get('/search', async (req, res) => {
const term = req.query.term;
const results = await Item.find({ name: { $regex: term } });
res.json(results);
});Users report no results even when matching items exist. What is the likely cause?
app.get('/search', async (req, res) => { const term = req.query.term; const results = await Item.find({ name: { $regex: term } }); res.json(results); });
Think about how MongoDB regex queries handle letter case.
MongoDB regex queries are case-sensitive by default. If the search term case does not match the stored data, no results appear. Adding the 'i' option makes it case-insensitive.
Consider this route that counts documents matching a condition:
app.get('/count', async (req, res) => {
const count = await Order.countDocuments({ status: 'shipped' });
res.send(`Shipped orders: ${count}`);
});If there are 7 orders with status 'shipped', what will be sent in the response?
app.get('/count', async (req, res) => { const count = await Order.countDocuments({ status: 'shipped' }); res.send(`Shipped orders: ${count}`); });
Recall what countDocuments returns when documents match the query.
The countDocuments method returns the number of documents matching the query. Here, it returns 7, so the response is 'Shipped orders: 7'.
When querying MongoDB in Express, what is the key difference between find() and findOne() methods?
Think about the return types of these methods.
find() returns an array of all documents matching the query, while findOne() returns the first matching document or null if none found.