Menu
CoddyTech

Comparing Numbers

Part of the Databases with MongoDB section of Coddy's Node.js journey. Lesson 8 of 29.

A filter can match an exact value or compare a numeric range. To match a range, use a comparison operator inside the field’s filter. $gte means greater than or equal to.

const minimum = Number(input.minimum);
const list = await products.find({price: {$gte: minimum}}).toArray();

Query-string values arrive as text. Convert a numeric limit with Number before comparing it with stored numbers. This example selects products whose price is at least the requested minimum. The result remains an array even if only one document matches. The next lesson combines optional filters on the bookshelf route.

challenge icon

Challenge

Easy

In exercise.js, return books whose numeric year is at least input.from. The server supplies that value from the query string. Return the matching documents, using the supplied collection.

Try GET /result?from=1960: Dune and Kindred match. Try ?from=1970: only Kindred matches. Try ?from=2000: return an empty array. Inputs in this exercise are valid numeric years.

Let the database compare years with $gte. A boundary of 1965 includes Dune as well as Kindred.

Try it yourself

export async function exercise(books, input) {
    return await books.find().toArray();
}

All lessons in Databases with MongoDB

Practice on your own: Express playground