{"_id":"keyv-mongodb-store","name":"keyv-mongodb-store","dist-tags":{"latest":"0.0.3"},"versions":{"0.0.3":{"name":"keyv-mongodb-store","version":"0.0.3","description":"A Keyv store implementation using MongoDB as the backend storage","type":"module","main":"./dist/index.js","module":"./dist/index.js","types":"./dist/index.d.ts","exports":{".":{"types":"./dist/index.d.ts","import":"./dist/index.js","default":"./dist/index.js"}},"keywords":["keyv","mongodb","storage","store","adapter","key-value","database","nosql"],"author":{"name":"snomiao"},"license":"MIT","repository":{"type":"git","url":"git+https://github.com/snomiao/keyv-mongodb-store.git"},"bugs":{"url":"https://github.com/snomiao/keyv-mongodb-store/issues"},"homepage":"https://github.com/snomiao/keyv-mongodb-store#readme","devDependencies":{"@biomejs/biome":"^2.3.8","@types/bun":"latest","keyv":"^5.0.0","mongodb":"^6.0.0","standard-version":"^9.5.0","typescript":"^5.9.3"},"peerDependencies":{"keyv":"^5.0.0","mongodb":"^6.0.0"},"scripts":{"build":"tsc","fmt":"biome check --unsafe --write","test":"bun test","prepack":"bun fmt && bun run build","release":"standard-version && git push --follow-tags && npm publish"},"engines":{"node":">=18.0.0"},"_id":"keyv-mongodb-store@0.0.3","gitHead":"bfb389be89648cdeac392c3243d16d6566976100","_nodeVersion":"24.5.0","_npmVersion":"11.5.2","dist":{"integrity":"sha512-8o6KnQkNWwYmiBXgiKeu9xg0Fp+ZcrE+xmdBvvscTvqO6s2piWTWPn4aOaj8j3LJT2AZ4/U2w9XVyTcHrJbStw==","shasum":"cff09def2f2bd2cced022b4704d87cfe5b63beba","tarball":"https://registry.npmjs.org/keyv-mongodb-store/-/keyv-mongodb-store-0.0.3.tgz","fileCount":7,"unpackedSize":27751,"signatures":[{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEQCIGa7onDSqG198biPAO+7MPw5oScRYq/8HMe3pzqji9b5AiA089k7HT0kQOlvWtVW72rRb1LXwjP3ZhvH9qTSkCCtSA=="}]},"_npmUser":{"name":"snomiao","email":"snomiao@gmail.com"},"directories":{},"maintainers":[{"name":"snomiao","email":"snomiao@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/keyv-mongodb-store_0.0.3_1765254117498_0.3827929645744126"},"_hasShrinkwrap":false}},"time":{"created":"2025-12-09T04:21:57.496Z","0.0.3":"2025-12-09T04:21:57.655Z","modified":"2025-12-09T04:21:57.959Z"},"maintainers":[{"name":"snomiao","email":"snomiao@gmail.com"}],"description":"A Keyv store implementation using MongoDB as the backend storage","homepage":"https://github.com/snomiao/keyv-mongodb-store#readme","keywords":["keyv","mongodb","storage","store","adapter","key-value","database","nosql"],"repository":{"type":"git","url":"git+https://github.com/snomiao/keyv-mongodb-store.git"},"author":{"name":"snomiao"},"bugs":{"url":"https://github.com/snomiao/keyv-mongodb-store/issues"},"license":"MIT","readme":"# keyv-mongodb-store\n\nA [Keyv](https://github.com/jaredwray/keyv) store implementation using [MongoDB](https://www.mongodb.com/) as the backend storage.\n\n## Features\n\n- **MongoDB-based storage** - Persistent key-value storage using MongoDB\n- **Flexible initialization** - Pass a MongoDB URI string, Database instance, or Collection instance\n- **Namespace support** - Organize your data with namespaces\n- **TTL support** - Set time-to-live for automatic key expiration\n- **Custom serialization** - Optional JSON serialization for complex data types\n- **TypeScript** - Fully typed with TypeScript support\n- **Native MongoDB features** - Leverages MongoDB's indexing and query capabilities\n- **Auto-connect** - Automatically connects when using URI string\n\n## Installation\n\n```bash\nbun install keyv-mongodb-store mongodb\n```\n\nOr with npm:\n\n```bash\nnpm install keyv-mongodb-store mongodb\n```\n\n## Usage\n\n### Basic Example with MongoDB URI (Recommended)\n\n```ts\nimport Keyv from \"keyv\";\nimport { KeyvMongodbStore } from \"keyv-mongodb-store\";\n\n// The simplest way - pass a MongoDB URI\n// Database name will be extracted from URI, defaults to \"keyv\" collection\nconst store = new KeyvMongodbStore(\"mongodb://localhost:27017/mydb\");\nconst keyv = new Keyv({ store });\n\n// Set a value\nawait keyv.set(\"foo\", \"bar\");\n\n// Get a value\nconst value = await keyv.get(\"foo\"); // \"bar\"\n\n// Delete a value\nawait keyv.delete(\"foo\");\n\n// Clear all values\nawait keyv.clear();\n\n// Don't forget to close the connection when done\nawait store.close();\n```\n\n### URI with Options\n\n```ts\n// Specify custom collection name and namespace\nconst store = new KeyvMongodbStore(\"mongodb://localhost:27017/mydb\", {\n  collectionName: \"cache\",\n  namespace: \"myapp\"\n});\n\n// Or override the database name from URI\nconst store2 = new KeyvMongodbStore(\"mongodb://localhost:27017\", {\n  dbName: \"customdb\",\n  collectionName: \"sessions\"\n});\n```\n\n### With Database Instance\n\n```ts\nimport Keyv from \"keyv\";\nimport { MongoClient } from \"mongodb\";\nimport { KeyvMongodbStore } from \"keyv-mongodb-store\";\n\nconst client = new MongoClient(\"mongodb://localhost:27017\");\nawait client.connect();\nconst db = client.db(\"mydb\");\n\n// Pass a database instance (will create/use a collection named \"keyv\")\nconst store = new KeyvMongodbStore(db);\nconst keyv = new Keyv({ store });\n\nawait keyv.set(\"foo\", \"bar\");\nconst value = await keyv.get(\"foo\"); // \"bar\"\n```\n\n### Using a Custom Collection Name\n\n```ts\nconst store = new KeyvMongodbStore(db, { collectionName: \"mycache\" });\nconst keyv = new Keyv({ store });\n\nawait keyv.set(\"user:1\", { name: \"Alice\" });\n```\n\n### Passing a Collection Instance Directly\n\n```ts\nconst collection = db.collection(\"keyv\");\nconst store = new KeyvMongodbStore(collection);\nconst keyv = new Keyv({ store });\n\nawait keyv.set(\"foo\", \"bar\");\n```\n\n### With Namespace\n\n```ts\nconst store = new KeyvMongodbStore(db, {\n  collectionName: \"cache\",\n  namespace: \"myapp\"\n});\n\nconst keyv = new Keyv({ store });\n\nawait keyv.set(\"user:1\", { name: \"Alice\" });\n// Stored with key: \"myapp:user:1\"\n```\n\n### With TTL (Time-To-Live)\n\nThis package uses MongoDB's native TTL (Time To Live) indexes for automatic document expiration. MongoDB automatically deletes expired documents in the background.\n\n```ts\nconst keyv = new Keyv({ store });\n\n// Set a value that expires in 1 second (1000ms)\nawait keyv.set(\"temp\", \"value\", 1000);\n\n// Wait for expiration\nawait new Promise(resolve => setTimeout(resolve, 1100));\n\nconst value = await keyv.get(\"temp\"); // undefined\n```\n\n**How TTL Works:**\n- When you set a TTL, the document's `expiresAt` field is set to a Date object\n- MongoDB's TTL index monitor runs every 60 seconds to remove expired documents\n- This implementation also includes immediate expiration checks during `get()` operations for instant feedback\n- No manual cleanup required - MongoDB handles it automatically!\n\n### With Custom Serialization\n\n```ts\nconst store = new KeyvMongodbStore(db, {\n  collectionName: \"cache\",\n  serializer: {\n    stringify: JSON.stringify,\n    parse: JSON.parse\n  }\n});\n\nconst keyv = new Keyv({ store });\n\n// Store complex objects\nawait keyv.set(\"user\", { id: 1, name: \"Alice\", roles: [\"admin\", \"user\"] });\n```\n\n## API\n\n### `new KeyvMongodbStore(uriOrDbOrCollection, options)`\n\nCreates a new MongoDB store instance.\n\n#### Parameters\n\n**`uriOrDbOrCollection`** - Can be one of three types:\n- **`string`** (MongoDB URI) - Automatically connects to MongoDB using the URI\n  - Example: `\"mongodb://localhost:27017/mydb\"`\n  - Database name is extracted from URI or use `dbName` option\n  - Connection is managed internally\n- **`Db`** (MongoDB Database instance) - Use an existing database connection\n  - A collection will be created/used based on `collectionName` option\n  - You manage the connection lifecycle\n- **`Collection`** (MongoDB Collection instance) - Use an existing collection directly\n  - The collection will be used as-is\n  - You manage the connection lifecycle\n\n#### Options\n\n- `dbName` (string, optional) - Database name (only used with URI, overrides URI database)\n- `collectionName` (string, optional) - Name of the collection to use (default: \"keyv\")\n- `namespace` (string, optional) - Prefix for all keys\n- `mongoClientOptions` (MongoClientOptions, optional) - MongoDB client options (only used with URI)\n- `serializer` (object, optional) - Custom serialization for values\n  - `stringify` (function) - Serialize value to string\n  - `parse` (function) - Deserialize string to value\n\n### Store Methods\n\nImplements the [Keyv Store Adapter](https://github.com/jaredwray/keyv#store-adapters) interface:\n\n- `get(key)` - Get a value by key\n- `getMany(keys)` - Get multiple values by keys (optimized with `$in` query)\n- `set(key, value, ttl?)` - Set a value with optional TTL in milliseconds\n- `delete(key)` - Delete a value by key\n- `clear()` - Clear all values (respects namespace)\n- `close()` - Close the MongoDB connection (only if created from URI)\n\n## Performance Features\n\n### Native MongoDB TTL Indexes\n\nThis implementation leverages MongoDB's native TTL (Time To Live) index feature:\n\n- **Automatic cleanup**: MongoDB automatically removes expired documents via background tasks\n- **Zero overhead**: No manual polling or cleanup logic needed\n- **Efficient**: Uses Date-based indexing for optimal performance\n- **Reliable**: MongoDB's TTL monitor runs every 60 seconds\n- **Immediate feedback**: Additional expiration checks in `get()` for instant response\n\n### Optimized Queries\n\n- **Unique index on key field**: Fast lookups with O(1) performance\n- **Batch operations**: `getMany()` uses MongoDB's `$in` operator for efficient multi-key retrieval\n- **Single query**: Fetches multiple documents in one database round-trip\n\n### Document Structure\n\n```javascript\n{\n  key: \"namespace:key\",           // Indexed for fast lookup\n  value: { /* any value */ },     // Your data\n  updatedAt: Date,                // Last update timestamp\n  expiresAt: Date                 // TTL expiration (indexed)\n}\n```\n\n## Why MongoDB?\n\nMongoDB is a powerful NoSQL database that:\n\n- Provides robust persistence and reliability\n- Scales horizontally for large datasets\n- Supports advanced indexing and querying\n- Offers built-in replication and sharding\n- Works well in distributed systems\n- Has excellent tooling and monitoring\n\nPerfect for:\n\n- Production applications\n- Large-scale caching\n- Distributed systems\n- Applications already using MongoDB\n- Scenarios requiring advanced querying\n\n## Comparison with keyv-nedb-store\n\n| Feature | keyv-mongodb-store | keyv-nedb-store |\n|---------|-------------------|-----------------|\n| Database | MongoDB (server) | NeDB (embedded) |\n| Initialization | URI / Db / Collection | File path / Options |\n| Scalability | Horizontal scaling | Single instance |\n| Query capabilities | Advanced | Basic |\n| Best for | Production, distributed systems | Development, small apps |\n| Setup complexity | Requires MongoDB server | Zero setup |\n| URI support | ✅ Supported | ❌ Not applicable |\n| Collection instance | ✅ Supported | ❌ Not applicable |\n\n## Development\n\nBuilt with [Bun](https://bun.com):\n\n```bash\n# Install dependencies\nbun install\n\n# Format code\nbun run fmt\n\n# Build\nbun run build\n```\n\n## License\n\nMIT\n\n## Related\n\n- [Keyv](https://github.com/jaredwray/keyv) - Simple key-value storage with support for multiple backends\n- [MongoDB](https://www.mongodb.com/) - The most popular NoSQL database\n- [keyv-nedb-store](https://github.com/snomiao/keyv-nedb-store) - NeDB-based store for embedded use cases\n","readmeFilename":"README.md","_rev":"1-1ca4afb6bd499c098d670b810d5a5834"}