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 🙏

© 2025 – Pkg Stats / Ryan Hefner

mm_mongodb

v1.5.3

Published

MongoDB数据库操作模块,提供简洁易用的API、缓存功能以及完整的Redis兼容接口,支持事件系统、事务和连接池管理

Readme

mm_mongodb

A powerful MongoDB database operation module with Redis-compatible API, connection pooling, and event system support.

npm version License Node.js Version

Features

  • Complete Redis-compatible API - Use familiar Redis commands with MongoDB
  • Connection Pool Management - Efficient connection pooling with automatic reconnection
  • Transaction Support - Full ACID transactions with session management
  • Event System - Comprehensive event system for monitoring operations
  • Index Management - Easy index creation and management
  • TTL Support - Automatic data expiration with TTL indexes
  • Environment Variable Configuration - Flexible configuration via environment variables
  • Query Injection Protection - Built-in security against NoSQL injection
  • Performance Optimized - Optimized for high-performance database operations

Installation

npm install mm_mongodb

Quick Start

Basic Usage

const { MongoDB } = require('mm_mongodb');

// Create MongoDB instance
const db = new MongoDB();

// Connect to database
await db.open();

// Create collection
await db.createTable('users');

// Insert data
await db.insert('users', { name: 'John', age: 25 });

// Query data
const result = await db.get('users', { name: 'John' });

// Update data
await db.set('users', { name: 'John' }, { age: 26 });

// Delete data
await db.del('users', { name: 'John' });

// Close connection
await db.close();

Redis-Compatible API

const { mongodb_cache_admin } = require('mm_mongodb');

// Get Redis-compatible cache instance
const cache = mongodb_cache_admin('default');

// Connect to database
await cache.open();

// Use Redis-style commands
await cache.set('name', 'Redis Compatible');
const value = await cache.get('name');
await cache.del('name');

// Hash operations
await cache.hset('user:1', 'name', 'John');
const name = await cache.hget('user:1', 'name');

// List operations
await cache.lpush('messages', 'Hello');
await cache.rpush('messages', 'World');
const messages = await cache.lrange('messages', 0, -1);

// Set operations
await cache.sadd('users:online', 'user1', 'user2');
const members = await cache.smembers('users:online');

Configuration

Environment Variables

Configure MongoDB connection via environment variables:

MONGO_URL=mongodb://username:password@host:port/database
MONGO_HOST=localhost
MONGO_PORT=27017
MONGO_USERNAME=username
MONGO_PASSWORD=password
MONGO_DATABASE=database
MONGO_AUTH_SOURCE=admin

Configuration File

Create config.tpl.json in your project root:

{
    "mongodb": {
        "url": "mongodb://username:password@host:port/database",
        "poolSize": 20,
        "minPoolSize": 5,
        "maxPoolSize": 100,
        "waitQueueTimeoutMS": 10000,
        "connectTimeoutMS": 10000,
        "socketTimeoutMS": 45000,
        "authSource": "admin",
        "authMechanism": "DEFAULT"
    }
}

API Documentation

Core MongoDB Class

Constructor

new MongoDB(scope = 'default', dir = '', config = {})

Connection Management

  • open() - Connect to database
  • close() - Close database connection
  • setUrl(url) - Set connection URL
  • setConfig(config) - Set configuration

Collection Operations

  • createTable(tableName) - Create collection
  • dropTable(tableName) - Drop collection
  • existsTable(tableName) - Check if collection exists

Data Operations

  • insert(tableName, data) - Insert document
  • insertBatch(tableName, datas) - Batch insert documents
  • get(tableName, query, options) - Query documents
  • getOne(tableName, query, options) - Query single document
  • set(tableName, query, data, options) - Update documents
  • del(tableName, query, options) - Delete documents
  • count(tableName, query) - Count documents

Transaction Support

  • startTransaction() - Start transaction
  • commitTransaction(session) - Commit transaction
  • rollbackTransaction(session) - Rollback transaction

Index Management

  • createIndex(tableName, keys, options) - Create index
  • createTTLIndex(tableName, keys, expireAfterSeconds) - Create TTL index
  • getIndexes(tableName) - Get index information
  • dropIndex(tableName, indexName) - Drop index

Redis-Compatible API

Key-Value Operations

  • set(key, value, seconds) - Set key with optional expiration
  • get(key) - Get value by key
  • del(key) - Delete key
  • has(key) / exists(key) - Check if key exists
  • clear(prefix) - Clear keys with optional prefix
  • keys(pattern) - Get matching keys
  • ttl(key) - Get time to live
  • expire(key, seconds) - Set expiration time
  • add(key, value) - Add key if not exists

Hash Operations

  • hset(key, field, value) - Set hash field
  • hget(key, field) - Get hash field
  • hgetall(key) - Get all hash fields
  • hmset(key, object) - Set multiple hash fields
  • hmget(key, ...fields) - Get multiple hash fields
  • hdel(key, field) - Delete hash field
  • hdelMulti(key, ...fields) - Delete multiple hash fields
  • hexists(key, field) - Check if hash field exists
  • hkeys(key) - Get all hash field names
  • hvals(key) - Get all hash field values
  • hlen(key) - Get number of hash fields

List Operations

  • lpush(key, value) - Push to left of list
  • rpush(key, value) - Push to right of list
  • lrange(key, start, stop) - Get list range
  • lindex(key, index) - Get list element by index
  • llen(key) - Get list length
  • lpop(key) - Pop from left of list
  • rpop(key) - Pop from right of list
  • lset(key, index, value) - Set list element by index
  • lrem(key, count, value) - Remove list elements
  • ltrim(key, start, stop) - Trim list

Set Operations

  • sadd(key, ...members) - Add set members
  • saddMulti(key, ...members) - Add multiple set members
  • srem(key, member) - Remove set member
  • sremMulti(key, ...members) - Remove multiple set members
  • smembers(key) - Get all set members
  • scard(key) - Get set size
  • sismember(key, member) - Check if member exists in set
  • sdiff(key1, key2) - Get set difference
  • sinter(key1, key2) - Get set intersection
  • sunion(key1, key2) - Get set union

Sorted Set Operations

  • zadd(key, member, score) - Add sorted set member
  • zrem(key, member) - Remove sorted set member
  • zrangebyscore(key, min, max) - Get members by score range
  • zscore(key, member) - Get member score
  • zcard(key) - Get sorted set size

Batch Operations

  • mset(object) - Set multiple keys
  • mget(...keys) - Get multiple keys
  • del(...keys) - Delete multiple keys

Numeric Operations

  • incr(key) - Increment by 1
  • decr(key) - Decrement by 1
  • addInt(key, value) - Add integer value
  • addFloat(key, value) - Add float value
  • addStr(key, value) - Append string

Event System

mm_mongodb provides a comprehensive event system for monitoring database operations:

const db = new MongoDB();
await db.open();

// Listen to operation events
db.on('set_before', (data) => {
    console.log('Before set operation:', data);
});

db.on('set_after', (data) => {
    console.log('After set operation:', data);
});

db.on('set_error', (data) => {
    console.error('Set operation error:', data);
});

// Trigger events
await db.set('test_key', 'test_value');

Supported Events

  • {action}_before - Before operation execution
  • {action}_after - After operation completion
  • {action}_error - On operation error

Where {action} can be: set, del, add, hset, lpush, sadd, zadd, etc.

Performance Optimization

  1. Use Connection Pooling - Always use mongodb_admin or mongodb_cache_admin for connection pooling
  2. Create Appropriate Indexes - Index frequently queried fields
  3. Use Batch Operations - Prefer mset, mget, insertBatch for multiple operations
  4. Set Expiration Times - Use TTL indexes for temporary data
  5. Optimize Queries - Avoid full collection scans, use precise queries

Migration from Redis

Migrating from Redis to mm_mongodb is straightforward:

// Redis client (original)
// const redis = require('redis');
// const client = redis.createClient();
// await client.connect();

// mm_mongodb (replacement)
const { mongodb_cache_admin } = require('mm_mongodb');
const cache = mongodb_cache_admin('default');
await cache.open();

// Your Redis commands remain the same
await cache.set('key', 'value');
const value = await cache.get('key');

Security Considerations

  • Passwords are automatically URI-encoded for secure transmission
  • Built-in query injection protection
  • Environment variables for sensitive configuration
  • Automatic connection retry for improved stability
  • Avoid using raw user input in queries

Dependencies

Compatibility

  • Node.js: >= 14.0.0 (Recommended: 16.0.0+)
  • MongoDB: 4.0+

Contributing

We welcome contributions! Please follow these steps:

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature/your-feature
  3. Commit your changes: git commit -m "feat: add your feature"
  4. Push to the branch: git push origin feature/your-feature
  5. Submit a pull request

Issues and Support

If you encounter any issues or have questions:

License

This project is licensed under the MIT License - see the LICENSE file for details.

Author

Qiu Wenwu - qww.elins.cn

Acknowledgments

Thanks to all contributors and users who have helped improve mm_mongodb!