Query Filters
Part of the Databases with MongoDB section of Coddy's Node.js journey. Lesson 4 of 18.
A client often wants only some books, and the database can do the picking.
The object you pass to find is a filter: a document matches when every field in the filter matches. A plain value means equal. An operator is a key that starts with $ and compares instead: $gte means greater than or equal, $lte less than or equal.
// paid orders of 20 or more
await orders.find({ status: 'paid', total: { $gte: 20 } }).toArray();Types count: { $gte: '20' } compares a string, and MongoDB never matches a string against a number field. Everything in req.query is a string, so turn numbers into numbers with Number() before they go into a filter.
Challenge
EasyGET /books filters by its query:
?author=keeps that author's books.?from=and?to=keep books published in those years, both ends included. Either can come alone.- No query lists every book.
Send GET /books?from=1960&to=1980, then GET /books?from=1970.
Try it yourself
import express from 'express';
import { MongoClient, ObjectId } from 'mongodb';
const client = new MongoClient('mongodb://localhost:27017');
const db = client.db('shelf');
const books = db.collection('books');
await books.insertMany([
{ title: 'Dune', author: 'Frank Herbert', year: 1965, isbn: '9780441013593', genre: 'scifi' },
{ title: 'Kindred', author: 'Octavia E. Butler', year: 1979, isbn: '9780807083697', genre: 'scifi' },
{ title: 'Emma', author: 'Jane Austen', year: 1815, isbn: '9780141439587', genre: 'classic' },
]);
const app = express();
app.use(express.json());
// Every error answers { error: message }.
function sendError(res, status, message) {
res.status(status).json({ error: message });
}
app.get('/', (req, res) => {
res.send('Bookshelf API');
});
app.get('/books', async (req, res) => {
const list = await books.find().toArray();
res.json(list);
});
app.post('/books', async (req, res) => {
const book = req.body;
await books.insertOne(book);
res.status(201).json(book);
});
app.get('/books/:id', async (req, res) => {
if (!ObjectId.isValid(req.params.id)) {
return sendError(res, 400, 'Not a valid id');
}
const book = await books.findOne({ _id: new ObjectId(req.params.id) });
if (!book) {
return sendError(res, 404, 'No such book');
}
res.json(book);
});
app.listen(3000, () => {
console.log('Bookshelf is running on port 3000');
});
All lessons in Databases with MongoDB
1Documents
Connecting to MongoDBInserting Documents