{"id":13480925,"url":"https://github.com/TylerBrock/mongo-hacker","last_synced_at":"2025-03-27T11:31:12.282Z","repository":{"id":4597980,"uuid":"5740758","full_name":"TylerBrock/mongo-hacker","owner":"TylerBrock","description":"MongoDB Shell Enhancements for Hackers","archived":false,"fork":false,"pushed_at":"2022-09-17T18:08:41.000Z","size":922,"stargazers_count":1782,"open_issues_count":5,"forks_count":235,"subscribers_count":61,"default_branch":"master","last_synced_at":"2025-03-23T15:43:44.992Z","etag":null,"topics":["database","javascript","mongodb","shell-extension"],"latest_commit_sha":null,"homepage":"tylerbrock.github.io/mongo-hacker","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/TylerBrock.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2012-09-09T19:16:40.000Z","updated_at":"2025-03-16T02:28:15.000Z","dependencies_parsed_at":"2022-08-27T13:32:48.069Z","dependency_job_id":null,"html_url":"https://github.com/TylerBrock/mongo-hacker","commit_stats":null,"previous_names":[],"tags_count":16,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/TylerBrock%2Fmongo-hacker","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/TylerBrock%2Fmongo-hacker/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/TylerBrock%2Fmongo-hacker/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/TylerBrock%2Fmongo-hacker/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/TylerBrock","download_url":"https://codeload.github.com/TylerBrock/mongo-hacker/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":245836068,"owners_count":20680313,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["database","javascript","mongodb","shell-extension"],"created_at":"2024-07-31T17:00:46.612Z","updated_at":"2025-03-27T11:31:11.980Z","avatar_url":"https://github.com/TylerBrock.png","language":"JavaScript","funding_links":[],"categories":["JavaScript","Tools"],"sub_categories":["Shell"],"readme":"\n            ┌───────────────────────────────────────────────────────────────────────────────────┐\n            │           __  ___                           __  __           __                   │\n            │          /  |/  /___  ____  ____ _____     / / / /___ ______/ /_____  _____       │\n            │         / /|_/ / __ \\/ __ \\/ __ `/ __ \\   / /_/ / __ `/ ___/ //_/ _ \\/ ___/       │\n            │        / /  / / /_/ / / / / /_/ / /_/ /  / __  / /_/ / /__/ ,\u003c /  __/ /           │\n            │       /_/  /_/\\____/_/ /_/\\__, /\\____/  /_/ /_/\\__,_/\\___/_/|_|\\___/_/            │\n            │                          /____/                                                   │\n            └───────────────────────────────────────────────────────────────────────────────────┘\n\n**This project has not been maintained for quite some time! [MongoSH](https://github.com/mongodb-js/mongosh) is now available.**\n\nPlease prefer using [MongoSH](https://github.com/mongodb-js/mongosh)!\n\nContinue at your own risk...\n\n\n# MongoDB Shell Enhancements\n\n## Warnings\n\n* These enhancements are useful to me but they don't make sense for everyone. Feel free to tweak to your desire and please submit [feedback or pull requests](https://github.com/TylerBrock/mongo-hacker/issues).\n* Only tested with non-EOL versions of MongoDB server (currently 3.4+)\n* Does not work with `mongo` shell or MongoDB servers \u003c 2.4\n* Updates called on existing cursors are experimental (see notes in API section)\n\n## Installation\n\n```sh\nnpm install -g mongo-hacker\nmongo\n```\n\n\n#### Install from source\n```\ngit clone https://github.com/TylerBrock/mongo-hacker\ncd mongo-hacker\nmake install\ncd ..\nrm -rdf mongo-hacker/\nmongo\n```\n\n## Enhancements\n\n#### Basic UX\n\n  - Verbose shell is enabled by default (config: `verbose_shell`)\n    - To toggle temporarily run `setVerboseShell(false)`\n  - Highlight query time if verbose shell is enabled\n    - In **green** if query time is at or below slowms\n    - In **red** if query time is above slowms\n  - Default indent is 2 spaces instead of tab (config: `indent`)\n  - Disable notification of \"Type 'it' for more\"\n  - Option to sort document keys (config: `sort_keys`)\n  - Custom prompt: `hostname(process-version)[rs_status:set_name] db\u003e`\n  - Always pretty print. You can still use default format by appending `.ugly()` to the end of a statement.\n  - Colorized query output for console/terminal windows supporting ANSI color codes.\n    ![Colorized Output](http://tylerbrock.github.com/mongo-hacker/screenshots/colorized_shell.png)\n\n#### Additional shell commands\n\nThe MongoDB shell offers various \"shell commands\" _(sometimes referred to as \"shell helpers\" as well)_ that make interactive use of the shell much more convenient than [proper, Javascript-only scripted use of the shell][interactive_versus_scripted].\n\nTo make interactive use of the MongoDB shell even more convenient, `mongo-hacker` adds the following shell commands:\n\n* `count collections`/`count tables`: count the number of collections in each of the mongo server's databases\n* `count documents`/`count docs`: count the number of documents in all _(non-`system`)_ collections in the database\n* `count indexes`: list all collections and display the size of all indexes\n\nSome of these commands have hidden features that can be enabled in the `mongo-hacker` config, to make the command output even more useful:\n\n* by changing the `count_deltas` setting to `true` in `config.js`, the `count documents` command will also print out the change in the number of documents since the last count\n\n[interactive_versus_scripted]: http://docs.mongodb.org/manual/tutorial/write-scripts-for-the-mongo-shell/#differences-between-interactive-and-scripted-mongo\n\n#### API Additions\n\n##### Scripting\n\nGet a list of database names:\n\n```js\ndb.getMongo().getDatabaseNames()\n```\n\n_(note that this method is similar - functionality-wise and usage-wise - to the existing `db.getCollectionNames()` API method and allows for advanced, cross-database scripting in the MongoDB shell)_\n\n##### General\n\nOne for finding a single document:\n\n```js\ndb.collection.find({ ... }).one() == db.collection.findOne({ ... })\n```\n\nSelect for selecting fields to return (projection):\n\n```js\ndb.collection.find({ ... }).select({ name: 1 })\n```\n\nReverse for descending sort by insertion order (default) or arbitrary field:\n\n```js\ndb.collection.find({ ... }).reverse()\ndb.collection.find({ ... }).reverse('createDate')\n```\n\nLast for finding last inserted document (default) or document last by given field:\n\n```js\ndb.collection.find({ ... }).last()\ndb.collection.find({ ... }).last('createDate')\n```\n\nUpdate, Replace, Upsert and Remove can be called on a DBQuery Object:\n\n```js\ndb.collection.find({ ... }).update({ ... })  // multi update\ndb.collection.find({ ... }).replace({ ... }) // single replacement\ndb.collection.find({ ... }).upsert({ ... })  // single upsert\ndb.collection.find({ ... }).remove()         // multi remove\n```\n\nSort, limit, and skip through multi updates and removes:\n\n```js\ndb.collection.find({ ... }).limit(7).update({ ... })\ndb.collection.find({ ... }).sort({ ... }).skip(1).limit(3).update({ ... })\ndb.collection.find({ ... }).limit(3).remove()\n```\n\n**Note**: *The performance of multi updates involving a skip or limit may be worse than those without those specifications due to there being absolutely no native support for this feature in MongoDB itself. It should be understood by the user of this software that use of this feature (by calling update on a cursor rather than a collection) is advanced and experimental. The option to do this sort of operation is purely additive to the MongoDB experience with MongoHacker and usage of it is in no way required. Furthermore, its inclusion in this enhancement does not effect the operation of updates invoked through collections and, in practice, is insanely useful.*\n\n\n#### Aggregation Framework\n\nThe aggregation framework is now fluent as well. You can use it as currently documented or via the chainable methods.\n\nCalling aggregate without an array of operations or $operations will make it a match.\n\n```js\n// matches every document\ndb.collection.aggregate()\ndb.collection.aggregate({})\n\n// matches documents where the \"a\" is equal to 1\ndb.collection.aggregate({a: 1})\n\n// matches documents where \"a\" is greater than 7\ndb.collection.aggregate({a: {$gt: 7}})\n```\n\nAdditional methods can then be chained on top of the inital match in order to make more complicated aggregations.\n\n```js\n// Match and project\ndb.collection.aggregate(\u003cquerydoc\u003e).project(\u003cprojection\u003e)\ndb.collection.aggregate({a: 1}).project({a: 1, _id: 0})\n\n// Match, group and sort\ndb.collection.aggregate({\u003cmatch\u003e}).group({\u003cgroup\u003e}).sort({\u003csort\u003e})\ndb.test.aggregate().group({_id: '$a', 'sum': {'$sum': 1}}).sort({sum: -1})\n```\n\n#### Data Generation\n\nFor easy and simple random data generation you can utilise these methods below. You can use any of these functions in a loop. For example: \n\n```js\n// Inserts 20 documents with random data. \nfor (i=1; i\u003c21; i++) { \n    db.collection.insert(\n            {\n             word: randomWord(), \n             number: randomNumber(), \n             date: randomDate() \n            }\n    ); \n}\n```\n\n##### randomWord \n\nYou can specify the length of each word, the number of words, and an optional seeded word in a sentence randomly. Use the optional `seed` parameter for testing text search.\n\n`randomWord(length=5, words=1, seed=undefined)` \n\n```js\n// Inserts a random sentence consisting of 5 letters per word, 5 words in total, \n// with a probability to insert the word 'needle' in the sentence\ndb.collection.insert( { words: randomWord(5, 5, 'needle') } )\n\n// Inserts a random word consisting of 16 letters\ndb.collection.insert( { words: randomWord(16) } )\n```\n\n##### randomNumber\n\nYou can specify maximum number to be randomly generated (exclusive)\n\n`randomNumber(max=100)`\n\n```js\n// Inserts a random number in the range of 0 or 1. \ndb.collection.insert( { number: randomNumber(2) } )\n\n// Inserts a random number in the range of 0 or 999. \ndb.collection.insert( { number: randomNumber(1000) } )\n\n```\n\n##### randomDate \n\nYou can specify start and end dates range to be randomly generated. (exclusive)\n\n`randomDate(start= \u003c2 years ago\u003e , end=Date() )`\n\n```js\n// Inserts a random date object in the range of 1st January 2016 to 1st February 2016\ndb.collection.insert( { date: randomDate(ISODate(\"2016-01-01T00:00:00\"), ISODate(\"2016-02-01T00:00:00\")) })\n\n// If today is 19th May 2016 and you specify only the start of the day, \n// this will generate random date object between 00:00:00 to current time.  \ndb.collection.insert( { date: randomDate(ISODate(\"2016-05-19T00:00:00\")) })\n```\n\n\n#### Helpers\n\nGeneral Shell Helpers\n\n  - `findCommand('search')` list commands that match the search string\n\n\nAggregation Framework Helpers -- on collections\n\n  - Group and Count: `gcount(group_field, filter)`\n  - Group and Sum: `gsum(group_field, sum_field, filter)`\n  - Group and Average: `gavg(group_field, avg_field, filter)`\n\nRun function on some/all databases\n\n```js\nrunOnDbs(/db_names_regexp/, function(db) {\n    // callback is ran for each database which name matches regular expression\n    // db is that selected database\n});\n```\n\n## Recent Changes\n\nSee [CHANGELOG.md](CHANGELOG.md) for a list of changes from previous versions of Mongo Hacker.\n\nA very special thanks to all of the [contributors to Mongo Hacker](https://github.com/TylerBrock/mongo-hacker/graphs/contributors).\n\n## Disclaimer\n\nThis software is not supported by [MongoDB, Inc.](https://www.mongodb.com/) under any of their commercial support subscriptions or otherwise. Any usage of Mongo Hacker is at your own risk. Bug reports, feature requests, and questions can be posted in the [Issues section](https://github.com/TylerBrock/mongo-hacker/issues?q=is%3Aopen+is%3Aissue) on GitHub.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FTylerBrock%2Fmongo-hacker","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FTylerBrock%2Fmongo-hacker","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FTylerBrock%2Fmongo-hacker/lists"}