CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-nedb

File-based embedded JavaScript database that provides persistent or in-memory data storage with a MongoDB-like API

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

query-system.mddocs/

Query System

Advanced querying capabilities with MongoDB-compatible operators for complex data retrieval, filtering, and update operations.

Capabilities

Comparison Operators

Standard comparison operators for numeric, string, and date comparisons.

/**
 * Comparison query operators
 */
interface ComparisonOperators {
  $lt: any;    // Less than
  $lte: any;   // Less than or equal to
  $gt: any;    // Greater than
  $gte: any;   // Greater than or equal to
  $ne: any;    // Not equal to
  $in: any[];  // Value exists in array
  $nin: any[]; // Value does not exist in array
}

Usage Examples:

const db = new Datastore({ filename: './products.db', autoload: true });

// Numeric comparisons
db.find({ price: { $lt: 100 } }, (err, cheapProducts) => {
  console.log('Products under $100:', cheapProducts);
});

db.find({ stock: { $gte: 10, $lte: 50 } }, (err, limitedStock) => {
  console.log('Products with limited stock:', limitedStock);
});

// String comparisons (lexicographic)
db.find({ category: { $ne: 'electronics' } }, (err, nonElectronics) => {
  console.log('Non-electronics products:', nonElectronics);
});

// Array membership
db.find({ category: { $in: ['books', 'music', 'movies'] } }, (err, media) => {
  console.log('Media products:', media);
});

db.find({ status: { $nin: ['discontinued', 'out-of-stock'] } }, (err, available) => {
  console.log('Available products:', available);
});

// Date comparisons
const lastMonth = new Date();
lastMonth.setMonth(lastMonth.getMonth() - 1);

db.find({ createdAt: { $gte: lastMonth } }, (err, recentProducts) => {
  console.log('Products added in the last month:', recentProducts);
});

String and Pattern Operators

Pattern matching and string-specific query operations.

/**
 * String and pattern operators
 */
interface PatternOperators {
  $regex: RegExp | string; // Regular expression match
  $exists: boolean;        // Field existence check
}

Usage Examples:

const db = new Datastore({ filename: './users.db', autoload: true });

// Regular expression matching
db.find({ email: { $regex: /@gmail\.com$/ } }, (err, gmailUsers) => {
  console.log('Gmail users:', gmailUsers);
});

// Case-insensitive regex with string
db.find({ name: { $regex: /^john/i } }, (err, johns) => {
  console.log('Users named John (case insensitive):', johns);
});

// Field existence checks
db.find({ phoneNumber: { $exists: true } }, (err, usersWithPhone) => {
  console.log('Users with phone numbers:', usersWithPhone);
});

db.find({ deletedAt: { $exists: false } }, (err, activeUsers) => {
  console.log('Active users (not deleted):', activeUsers);
});

// Combining regex with other operators
db.find({
  $and: [
    { email: { $regex: /@company\.com$/ } },
    { status: { $ne: 'inactive' } }
  ]
}, (err, activeEmployees) => {
  console.log('Active company employees:', activeEmployees);
});

Array Operators

Specialized operators for querying array fields and their contents.

/**
 * Array-specific operators
 */
interface ArrayOperators {
  $size: number;           // Array size equals specified number
  $elemMatch: object;      // At least one array element matches all criteria
}

Usage Examples:

const db = new Datastore({ filename: './orders.db', autoload: true });

// Array size matching
db.find({ items: { $size: 3 } }, (err, ordersWithThreeItems) => {
  console.log('Orders with exactly 3 items:', ordersWithThreeItems);
});

// Element matching in arrays
db.find({ 
  items: { 
    $elemMatch: { 
      category: 'electronics', 
      price: { $gt: 500 } 
    } 
  } 
}, (err, expensiveElectronicsOrders) => {
  console.log('Orders with expensive electronics:', expensiveElectronicsOrders);
});

// Array field value matching (direct)
db.find({ tags: 'urgent' }, (err, urgentOrders) => {
  // Matches documents where tags array contains 'urgent'
  console.log('Urgent orders:', urgentOrders);
});

// Multiple array conditions
db.find({
  $and: [
    { tags: { $size: { $gte: 2 } } },
    { tags: 'priority' }
  ]
}, (err, priorityOrders) => {
  console.log('Priority orders with multiple tags:', priorityOrders);
});

Logical Operators

Boolean logic for combining multiple query conditions.

/**
 * Logical operators for combining conditions
 */
interface LogicalOperators {
  $or: object[];        // Logical OR - at least one condition must match
  $and: object[];       // Logical AND - all conditions must match
  $not: object;         // Logical NOT - condition must not match
  $where: function;     // Custom function evaluation
}

Usage Examples:

const db = new Datastore({ filename: './products.db', autoload: true });

// OR conditions
db.find({
  $or: [
    { category: 'electronics' },
    { price: { $lt: 50 } },
    { featured: true }
  ]
}, (err, products) => {
  console.log('Electronics OR cheap OR featured products:', products);
});

// AND conditions (explicit)
db.find({
  $and: [
    { price: { $gte: 100 } },
    { stock: { $gt: 0 } },
    { rating: { $gte: 4.0 } }
  ]
}, (err, premiumProducts) => {
  console.log('Premium available products:', premiumProducts);
});

// NOT conditions
db.find({
  $not: { 
    category: { $in: ['discontinued', 'clearance'] } 
  }
}, (err, regularProducts) => {
  console.log('Regular products (not discontinued/clearance):', regularProducts);
});

// Custom function evaluation
db.find({
  $where: function() {
    return this.price > this.originalPrice * 0.5;
  }
}, (err, significantlyDiscounted) => {
  console.log('Products with >50% discount:', significantlyDiscounted);
});

// Complex nested logic
db.find({
  $and: [
    {
      $or: [
        { category: 'books' },
        { category: 'ebooks' }
      ]
    },
    {
      $not: { 
        status: 'out-of-print' 
      }
    },
    { price: { $lte: 30 } }
  ]
}, (err, affordableBooks) => {
  console.log('Affordable available books:', affordableBooks);
});

Update Operators

Operators for modifying documents without replacing them entirely.

/**
 * Update operators for document modification
 */
interface UpdateOperators {
  $set: object;         // Set field values
  $unset: object;       // Remove fields
  $inc: object;         // Increment numeric fields
  $push: object;        // Add elements to arrays
  $addToSet: object;    // Add unique elements to arrays
  $pop: object;         // Remove first/last array elements
  $pull: object;        // Remove matching array elements
  $min: object;         // Set to minimum value
  $max: object;         // Set to maximum value
}

/**
 * Array update modifiers
 */
interface ArrayUpdateModifiers {
  $each: any[];         // Apply operation to each element (used with $push, $addToSet)
  $slice: number;       // Limit array size after $push operation
}

Usage Examples:

const db = new Datastore({ filename: './users.db', autoload: true });

// Set field values
db.update(
  { name: 'Alice' },
  { $set: { status: 'premium', lastLogin: new Date() } },
  {},
  (err, numUpdated) => {
    console.log('Set status and lastLogin for Alice');
  }
);

// Remove fields
db.update(
  { status: 'deleted' },
  { $unset: { email: true, phoneNumber: true } },
  { multi: true },
  (err, numUpdated) => {
    console.log('Removed personal info from deleted accounts');
  }
);

// Increment numeric values
db.update(
  { name: 'Bob' },
  { $inc: { loginCount: 1, points: 10 } },
  {},
  (err, numUpdated) => {
    console.log('Incremented login count and points for Bob');
  }
);

// Array operations - push single element
db.update(
  { name: 'Charlie' },
  { $push: { tags: 'vip' } },
  {},
  (err, numUpdated) => {
    console.log('Added VIP tag to Charlie');
  }
);

// Array operations - push multiple elements with slice
db.update(
  { name: 'Diana' },
  { 
    $push: { 
      recentActivity: { 
        $each: ['login', 'purchase', 'review'],
        $slice: -5  // Keep only last 5 activities
      }
    }
  },
  {},
  (err, numUpdated) => {
    console.log('Added recent activities to Diana (keeping last 5)');
  }
);

// Add to set (unique elements only)
db.update(
  { name: 'Eve' },
  { $addToSet: { skills: { $each: ['javascript', 'python', 'javascript'] } } },
  {},
  (err, numUpdated) => {
    console.log('Added unique skills to Eve');
  }
);

// Remove array elements
db.update(
  { name: 'Frank' },
  { $pull: { tags: 'temporary' } },
  {},
  (err, numUpdated) => {
    console.log('Removed temporary tags from Frank');
  }
);

// Pop elements from array
db.update(
  { name: 'Grace' },
  { $pop: { notifications: 1 } }, // 1 for last, -1 for first
  {},
  (err, numUpdated) => {
    console.log('Removed last notification from Grace');
  }
);

// Min/Max operations
db.update(
  { name: 'Henry' },
  { 
    $min: { lowestScore: 85 },  // Set only if current value is higher
    $max: { highestScore: 92 }  // Set only if current value is lower
  },
  {},
  (err, numUpdated) => {
    console.log('Updated min/max scores for Henry');
  }
);

Nested Field Queries

Query and update nested object fields using dot notation.

/**
 * Dot notation for nested field access
 * Use string keys with dots to access nested properties
 */
interface DotNotation {
  'field.subfield': any;           // Access nested object properties
  'arrayField.0.property': any;    // Access array element properties
  'deep.nested.field': any;       // Access deeply nested properties
}

Usage Examples:

const db = new Datastore({ filename: './profiles.db', autoload: true });

// Sample document structure:
// {
//   name: 'John',
//   address: {
//     street: '123 Main St',
//     city: 'Boston',
//     coordinates: { lat: 42.3601, lng: -71.0589 }
//   },
//   orders: [
//     { id: 1, amount: 100, status: 'completed' },
//     { id: 2, amount: 250, status: 'pending' }
//   ]
// }

// Query nested object fields
db.find({ 'address.city': 'Boston' }, (err, bostonUsers) => {
  console.log('Users in Boston:', bostonUsers);
});

db.find({ 'address.coordinates.lat': { $gte: 40 } }, (err, northernUsers) => {
  console.log('Users in northern locations:', northernUsers);
});

// Query array elements
db.find({ 'orders.status': 'pending' }, (err, usersWithPending) => {
  console.log('Users with pending orders:', usersWithPending);
});

// Update nested fields
db.update(
  { name: 'John' },
  { $set: { 'address.street': '456 Oak Ave' } },
  {},
  (err, numUpdated) => {
    console.log('Updated Johns street address');
  }
);

// Update nested arrays
db.update(
  { 'orders.id': 2 },
  { $set: { 'orders.$.status': 'shipped' } },
  {},
  (err, numUpdated) => {
    console.log('Updated order status');
  }
);

Query Performance Tips

  • Create indexes on frequently queried fields using ensureIndex()
  • Use specific field values instead of complex operators when possible
  • Combine multiple conditions in a single query rather than chaining queries
  • Use projections to limit returned field data
  • Consider using findOne() when you only need a single result
  • Use $exists: false instead of $ne: null for better performance on missing fields

docs

cursor-operations.md

database-management.md

document-operations.md

index-management.md

index.md

query-system.md

tile.json