BugForge
All lessons
Databases · 03/09 6 min2 hands-on

Finding things: filters and operators

Filters are just objects. Add $gt, $in and $regex, then sort and limit the results.

A query is a plain object describing the documents you want.

Product.find({ inStock: true });                 // field equals value
Product.find({ price: { $lt: 20 } });            // operator: less than
Product.find({ price: { $gte: 10, $lte: 50 } }); // between, ends included
Product.find({ tags: "phone" });                 // array field CONTAINS "phone"
Product.find({ tags: { $in: ["phone", "apple"] } }); // contains any of these
Product.find({ name: { $regex: "phone", $options: "i" } }); // case-insensitive contains

Operator cheat sheet

Operator Means
$eq $ne equal / not equal
$gt $gte greater than / or equal
$lt $lte less than / or equal
$in $nin in / not in a list
$exists field is present
$or { $or: [{ a: 1 }, { b: 2 }] }

Shaping the result

Product.find(filter).sort({ price: 1 }).limit(5);   // 5 cheapest
Product.find(filter).sort({ price: -1 });           // most expensive first
Product.findOne({ name: "Lamp" });                  // first match or null
Product.countDocuments(filter);                     // just the number

find always returns an array (maybe empty). findOne and findById return a document or null.

A safety note

If user text goes into $regex, escape it. Otherwise a search for . matches everything, and ( crashes the query. Exercise 2 checks this.

Your turn · 2 exercises0/2 solved

Filter by price

Use comparison operators: cheaperThan(max) (strictly below, cheapest first) and inPriceRange(min, max) (both ends included).

Loading editor…
Next in Databases
Connect a database to an API