Querying Documents
Querying allows you to retrieve documents using filters, sorting, pagination and projection. low-json-db supports a rich set of MongoDB-style operators.
find() – Multiple Documents
// All documents
const all = users.find().toArray();
// With a filter
const adults = users.find({ age: { $gte: 18 } }).toArray();
// Multiple conditions (AND)
const result = users.find({
city: 'Lagos',
age: { $gt: 30 }
}).toArray();
findOne() – Single Document
const alice = users.findOne({ name: 'Alice' });
// returns the document or null
When the query is a simple equality on an indexed field, findOne uses the index for extremely fast lookup.
Query Builder Methods
find() returns a QueryBuilder that supports chaining:
const page = users
.find({ age: { $gte: 25 } })
.sort({ name: 1 })
.skip(0)
.limit(10)
.project({ name: 1, age: 1, city: 1 })
.toArray();
Available methods
| Method | Description |
|---|---|
limit(n) | Limit number of results |
skip(n) | Skip the first n results (pagination) |
sort({ field: 1 | -1 }) | Sort ascending (1) or descending (-1) |
project({ field: 1 }) | Include only selected fields |
toArray() | Execute and return all matching documents |
first() | Return only the first matching document |
count() | Return the number of matching documents |
Supported Query Operators
| Operator | Meaning | Example |
|---|---|---|
$eq | Equal | { age: { $eq: 30 } } |
$ne | Not equal | { status: { $ne: 'banned' } } |
$gt / $gte | Greater than / equal | { age: { $gte: 18 } } |
$lt / $lte | Less than / equal | { price: { $lt: 100 } } |
$in | Value is in array | { city: { $in: ['Lagos', 'Abuja'] } } |
$nin | Value is not in array | { role: { $nin: ['guest'] } } |
$exists | Field exists | { email: { $exists: true } } |
$regex | Regular expression | { name: { $regex: '^A', $options: 'i' } } |
$or / $and / $nor | Logical operators | { $or: [{ age: 20 }, { city: 'Lagos' }] } |
Nested Fields
// Documents that look like: { profile: { city: 'Lagos' } }
users.find({ 'profile.city': 'Lagos' }).toArray();
Next: Learn how to update documents.