Sikau

MongoDB · Day 2 · about 30 min

Querying documents

Filters, operators, nested fields and arrays.

Filters are documents too

In MongoDB you describe what you want with a filter document: { veg: true }. Query operators like $gt and $in handle ranges and lists, and dotted paths reach inside nested fields.

find(filter)

printjson(db.dishes.find({ veg: true }, { name: 1, _id: 0 }).toArray());

printjson(db.dishes.find({ price: { $gte: 200, $lt: 300 } }, { name: 1, price: 1, _id: 0 }).toArray());

printjson(db.dishes.find({ category: { $in: ["snack", "drink"] } }, { name: 1, _id: 0 }).toArray());

printjson(db.dishes.find({ tags: "popular" }, { name: 1, _id: 0 }).toArray());

printjson(db.dishes.find({ "ingredients.item": "chicken" }, { name: 1, _id: 0 }).toArray());

printjson(db.dishes.find({ $or: [{ price: { $lt: 100 } }, { tags: "spicy" }] }, { name: 1, _id: 0 }).toArray());

The rest of this lesson

  • Combining conditionsexplain
  • Missing fields and nullexplain
  • Matches?predict
  • Pick the filtermatch
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 15 lessons of MongoDB