npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@oxlayer/capabilities-adapters-mongo

v0.1.4

Published

MongoDB adapter for @oxlayer/capabilities

Readme

@oxlayer/capabilities-adapters-mongo

MongoDB adapter for @oxlayer/capabilities. Provides a simplified interface for MongoDB operations with automatic connection pooling and collection management.

Features

  • Simplified MongoDB client with connection pooling
  • CRUD operations (create, read, update, delete)
  • Aggregation pipelines
  • Index management
  • Collection statistics
  • Health check
  • Automatic query logging with timing
  • Support for transactions via pool client

Installation

bun add @oxlayer/capabilities-adapters-mongo

Dependencies

bun add mongodb

Usage

Basic Setup

import { createMongoClient } from '@oxlayer/capabilities-adapters-mongo';

const mongo = createMongoClient({
  url: 'mongodb://localhost:27017',
  database: 'mydb',
});

await mongo.connect();

// Find documents
const users = await mongo.find('users', {
  filter: { age: { $gte: 18 } },
  sort: { createdAt: -1 },
  limit: 10,
});

// Find one document
const user = await mongo.findOne('users', {
  filter: { email: '[email protected]' },
});

// Find by ID
const user = await mongo.findById('users', '507f1f77bcf86cd799439011');

await mongo.disconnect();

Insert Operations

// Insert single document
const user = await mongo.insert('users', {
  name: 'John Doe',
  email: '[email protected]',
  age: 30,
});

// Insert multiple documents
const count = await mongo.insertMany('users', [
  { name: 'Alice', email: '[email protected]' },
  { name: 'Bob', email: '[email protected]' },
]);
console.log(`Inserted ${count} documents`);

Update Operations

// Update one document
const updated = await mongo.update('users',
  { email: '[email protected]' }, // filter
  { $set: { age: 31 } },          // update
  { returnDocument: 'after' }     // options
);

// Update by ID
await mongo.updateById('users', '507f1f77bcf86cd799439011', {
  $set: { status: 'active' },
});

// Update multiple documents
const count = await mongo.updateMany('users',
  { status: 'pending' },
  { $set: { status: 'processed' } }
);

Delete Operations

// Delete one document
const deleted = await mongo.delete('users', { email: '[email protected]' });

// Delete by ID
await mongo.deleteById('users', '507f1f77bcf86cd799439011');

// Delete multiple documents
const count = await mongo.deleteMany('users', { status: 'deleted' });

Aggregation

const results = await mongo.aggregate('users', [
  { $match: { age: { $gte: 18 } } },
  { $group: { _id: '$city', count: { $sum: 1 } } },
  { $sort: { count: -1 } },
]);

Index Management

// Create single index
await mongo.createIndex('users', {
  keys: { email: 1 },
  options: { unique: true },
});

// Create multiple indexes
await mongo.createIndexes('users', [
  { keys: { email: 1 }, options: { unique: true } },
  { keys: { createdAt: -1 } },
  { keys: { name: 'text', email: 'text' } },
]);

// List indexes
const indexes = await mongo.listIndexes('users');

// Drop index
await mongo.dropIndex('users', 'email_1');

Collection Management

// Get collection statistics
const stats = await mongo.getCollectionStats('users');
console.log(stats.count, stats.size, stats.avgObjSize);

// List all collections
const collections = await mongo.listCollections();

// Drop collection
await mongo.dropCollection('temp_data');

Environment Variables

import { createDefaultMongoClient } from '@oxlayer/capabilities-adapters-mongo';

const mongo = createDefaultMongoClient();

// Uses environment variables:
// MONGO_URL=mongodb://localhost:27017
// MONGO_DATABASE=mydb

Transactions

// Get a client from the pool for transactions
const client = await mongo.getClient();
const session = client.startSession();

try {
  await session.withTransaction(async () => {
    const db = client.db();

    await db.collection('users').insertOne({ name: 'Alice' }, { session });
    await db.collection('logs').insertOne({ action: 'created' }, { session });
  });
} finally {
  await session.endSession();
}

API Reference

MongoClientWrapper

Main client class for MongoDB operations.

Constructor

constructor(config: MongoConfig)

Config:

  • url - MongoDB connection string (required)
  • database - Database name (required)
  • options - Connection pool options
    • maxPoolSize - Maximum pool size (default: 20)
    • minPoolSize - Minimum pool size (default: 2)
    • maxIdleTimeMS - Max idle time (default: 60000)
    • connectTimeoutMS - Connect timeout (default: 10000)
    • socketTimeoutMS - Socket timeout (default: 45000)
    • serverSelectionTimeoutMS - Server selection timeout (default: 30000)
    • appName - Application name (default: 'staples-mongo')

Methods

connect(): Promise<void>

Connect to MongoDB.

disconnect(): Promise<void>

Disconnect from MongoDB.

find<T>(collection, options?): Promise<T[]>

Find documents in a collection.

Options:

  • filter - Query filter
  • sort - Sort specification
  • skip - Number of documents to skip
  • limit - Maximum number of documents to return
  • projection - Field projection
findOne<T>(collection, options?): Promise<T | null>

Find a single document.

findById<T>(collection, id): Promise<T | null>

Find a document by ID.

count<T>(collection, filter?): Promise<number>

Count documents in a collection.

insert<T>(collection, document): Promise<T>

Insert a document and return the inserted document.

insertMany<T>(collection, documents): Promise<number>

Insert multiple documents and return count.

update<T>(collection, filter, update, options?): Promise<T | null>

Update a document and return the updated document.

updateById<T>(collection, id, update, options?): Promise<T | null>

Update a document by ID.

updateMany<T>(collection, filter, update): Promise<number>

Update multiple documents and return count.

delete<T>(collection, filter): Promise<T | null>

Delete a document and return it.

deleteById<T>(collection, id): Promise<T | null>

Delete a document by ID.

deleteMany<T>(collection, filter): Promise<number>

Delete multiple documents and return count.

aggregate<T>(collection, pipeline): Promise<T[]>

Execute an aggregation pipeline.

createIndex(collection, spec): Promise<string>

Create an index on a collection.

createIndexes(collection, specs): Promise<string[]>

Create multiple indexes.

dropIndex(collection, indexName): Promise<void>

Drop an index from a collection.

listIndexes(collection): Promise<Array<{ name, key }>>

List indexes on a collection.

getCollectionStats(collection): Promise<CollectionStats>

Get collection statistics.

dropCollection(collection): Promise<void>

Drop a collection.

listCollections(): Promise<string[]>

List all collections.

healthCheck(): Promise<boolean>

Check if connection is healthy.

getClient(): MongoClient

Get the underlying MongoDB client.

getDb(): Db

Get the underlying MongoDB Db instance.

isConnected(): boolean

Check if the client is connected.

Types

MongoConfig

interface MongoConfig {
  url: string;
  database: string;
  options?: {
    maxPoolSize?: number;
    minPoolSize?: number;
    maxIdleTimeMS?: number;
    connectTimeoutMS?: number;
    socketTimeoutMS?: number;
    serverSelectionTimeoutMS?: number;
    appName?: string;
  };
}

FindOptions<T>

interface FindOptions<T> {
  filter?: Filter<T>;
  sort?: Sort;
  skip?: number;
  limit?: number;
  projection?: Record<string, 1 | 0>;
}

CollectionStats

interface CollectionStats {
  name: string;
  count: number;
  size: number;
  avgObjSize: number;
  indexCount: number;
  indexSize: number;
}

Query Operators

Use MongoDB query operators:

// Comparison
await mongo.find('users', { filter: { age: { $gte: 18, $lt: 65 } } });

// Logical
await mongo.find('users', { filter: { $or: [{ active: true }, { verified: true }] } });

// Arrays
await mongo.find('posts', { filter: { tags: { $in: ['javascript', 'typescript'] } } });

Best Practices

  1. Use connection pooling: Reuse client across requests
  2. Index frequently queried fields: Create appropriate indexes
  3. Use projections: Limit returned fields for better performance
  4. Monitor connection pool: Check pool statistics
  5. Handle transactions: Use sessions for multi-document operations

Error Handling

The adapter logs all query errors:

try {
  await mongo.find('users', { filter: { $invalid: true } });
} catch (error) {
  console.error('Query failed:', error);
}

License

MIT