open-index/open-npm huggingface dataset:
npm package: @mongosh/autocomplete
Description: MongoDB Shell Autocomplete Package
Latest version: 5.1.6

# `@mongosh/autocomplete`

Package for [MongoDB Shell](mongosh)

## Usage

```js
const autocomplete = require('@mongosh/autocomplete');
const serverVersion = '4.4.0';
const line = 'db.coll.fin';
const completions = autocomplete(serverVersion, line);
if (!completions || !completions.length) {
  return [];
}
const entries = completions[0].map((completion) => {
  return {
    completion,
  };
});
```

### API

#### completions = autocomplete(serverVersion, line)

**serverVersion:** current version of MongoDB
**line:** current line to autcomplete

Returns an array of completions, and the line we were autocompleting. For
example:

```js
const autocomplete = require('@mongosh/autocomplete');
const serverVersion = '4.4.0';
const line = 'db.coll.re';
const completions = autocomplete(serverVersion, line);
// returns:
// [
//   [ 'db.coll.renameCollection', 'db.coll.replaceOne', 'db.coll.reIndex' ],
//   'db.coll.re'
// ]
```

Autocomplete is based on currently implemented APIs in [@mongosh/shell-api](https://www.npmjs.com/package/@mongosh/shell-api)

## Installation

```shell
npm install -S @mongosh/errors
```

[mongosh]: https://github.com/mongodb-js/mongosh
npm package: @mongosh/browser-repl
Description: Browser presentation component for Mongo Shell
Latest version: 5.3.4

# Browser Repl

React Browser component for Mongo Shell

## Usage

```js
import { Shell } from 'mongosh-browser-repl';

export () => {
  return <Shell runtime={runtime} />;
}
```

### Built-in Runtimes

#### IframeRuntime

Uses an iframe window as sandbox for code execution. **NOTE:** the execution is not really sandboxed, the top window is accessible.

```js
import { IframeRuntime } from 'mongosh-browser-repl';

const runtime = new IframeRuntime(serviceProvider);
```

## API

### `<Shell />`

Shell is a React component with the following properties:

- `runtime: Runtime`: The runtime used to evaluate code.
- `onOutputChanged?: (output: ShellOutputEntry[]) => void`: A function called each time the output changes with an array of `ShellOutputEntries`.
- `onHistoryChanged?: (history: string[]) => void`: A function called each time the history changes with an array of history entries ordered from the most recent to the oldest entry.
- `onEditorChanged?: (editor: EditorRef | null) => void`: A function called each time the editor ref changes. Can be used to call editor methods.
- `onOperationStarted?: () => void`: A function called when an operation has begun.
- `onOperationEnd?: () => void`: A function called when an operation has completed (both error and success).
- `redactInfo?: boolean`: If set, the shell will omit or redact entries containing sensitive info from history. Defaults to `false`.
- `maxOutputLength?: number`: The maxiumum number of lines to keep in the output. Defaults to `1000`.
- `maxHistoryLength?: number`: The maxiumum number of lines to keep in the history. Defaults to `1000`.
- `initialEvaluate?: string|string[]`: A set of input strings to evaluate right after shell is mounted.
- `initialText?: string`: The initial text for the input field.
- `output?: ShellOutputEntry[]`: An array of entries to be displayed in the output area. Can be used to restore the output between sessions, or to setup a greeting message. **Note**: new entries will not be appended to the array.
- `history?: readonly string[]`: An array of history entries to prepopulate the history.
  Can be used to restore the history between sessions. Entries must be ordered from the most recent to the oldest. Note: new entries will not be appended to the array.
- `isOperationInProgress?: boolean`: Can be used to restore the value between sessions.

### `ShellOutputEntry`

An object representing an entry in the shell output, with the following properties:

- `format: 'input' | 'output' | 'error'`: the type of the entry
- `type?: string`: the shell api type if the entry value is a shell api object.
- `value: any`: the value that has to be rendered in output.
npm package: @mongosh/browser-runtime-core
Description: Mongosh browser runtime core
Latest version: 5.3.4

# browser-runtime-core

Core and support classes and types used by runtimes.

## Api

### `Runtime`

Encapsulates the details of evaluation logic exposing an implementation
agnostic interface.

All runtimes implement the following interface:

- `evaluate(code: string): Promise<ShellResult>`: Evaluates a string of code.

### `ShellResult`

An object holding the result of an evaluation. Has the following properties:

- `type: string`: the shell api type if the entry value is a shell api object.
- `value: any`: the value that has to be rendered in output.
npm package: @mongosh/browser-runtime-electron
Description: Mongosh browser runtime electron
Latest version: 5.3.4

# browser-runtime-electron

## ElectronRuntime

`Runtime` implementation that uses Node.js `vm` module as sandbox for
code execution.

```js
import { ElectronRuntime } from 'mongosh-browser-repl';

const runtime = new ElectronRuntime(serviceProvider);
```

##### Example: usage in Compass

```js
import { Shell, ElectronRuntime } from 'mongosh-browser-repl';

const runtime = new ElectronRuntime(
  await CompassServiceProvider.connect(...)
);

function MyShell(props) {
  return <Shell runtime={runtime} />;
}
```
npm package: @mongosh/js-multiline-to-singleline
Description: Make multiline JS into a single line
Latest version: 2.4.13

# `@mongosh/js-multiline-to-singleline`

Package for [MongoDB Shell](https://github.com/mongodb-js/mongosh).

### Installation

```shell
npm install -S @mongosh/js-multiline-to-singleline
```
npm package: @mongosh/shell-bson
Description: mongosh-style BSON handling
Latest version: 3.0.3

# `@mongosh/shell-bson`

> Expose MongoDB Shell BSON classes based on the Node.js driver BSON package

## Usage

```js
import { constructShellBson, makePrintableBson } from '@mongosh/shell-bson';
import * as bson from 'bson';
import * as vm from 'vm';

// Optional: Get shell-compatible pretty-printing for BSON objects
// when used with Node.js's custom inspect() functionality
makePrintableBson(bson);

// Create Shell-like BSON helpers
const shellBson = constructShellBson({
  bsonLibrary: bson,
  printWarning: console.warn,
});

// Evaluate code against Shell-like BSON helpers
const document = vm.runInNewContext(
  '({ uuid: UUID(), dec128: NumberDecimal("12.34") })',
  { ...shellBson }
);
```
npm package: @mongosh/snippet-ai
Description: Provides an AI command suite for mongosh to ask for MongoDB query expressions in natural language.
Author: Gagik Amaryan
Latest version: 0.1.4

# AI Snippets for mongosh

> [!CAUTION]
> This is an experimental snippet that is not meant for production use. 

This snippet adds a suite of commands accessible with the `ai` command. This includes:

|  |  |  |
|---------|-------------|---------|
| `ai <question>` | Ask questions about MongoDB | `ai.ask how do I run queries in mongosh?` |
| `ai.cmd` | Generate general mongosh commands _alias:_ `ai.cmd` | `ai.cmd get sharding info` |
| `ai.find` | Generate queries and aggregations based on natural language | `ai.find users with age > 30` |
| `ai.collection` | Set the active collection | `ai.collection users` |
| `ai.config` | Configure the AI commands | `ai.config.set("provider", "ollama")` |

This currently supports 4 different AI providers: `mongodb`, `openai` (requires `MONGOSH_AI_OPENAI_API_KEY` environment variable to be set), `mistral` (requires `MONGOSH_AI_MISTRAL_API_KEY`) and `ollama`.

## Installation

You can install this snippet using the `snippet` command in mongosh:

```javascript
snippet install ai
```

## License

This snippet is licensed under the Apache-2.0 license.
npm package: @mongosh/snippet-analyze-schema
Description: schema(db.coll)
Latest version: 1.0.6

# analyze-schema

Analyze the schema of a collection or a cursor.

```js
> schema(db.coll);
┌─────────┬───────┬───────────┬────────────┐
│ (index) │   0   │     1     │     2      │
├─────────┼───────┼───────────┼────────────┤
│    0    │ '_id' │ '100.0 %' │ 'ObjectID' │
│    1    │ 'a  ' │ '50.0 %'  │  'Number'  │
│    2    │ 'a  ' │ '50.0 %'  │  'String'  │
└─────────┴───────┴───────────┴────────────┘
> schema(db.coll.find({ }));
┌─────────┬───────┬───────────┬────────────┐
│ (index) │   0   │     1     │     2      │
├─────────┼───────┼───────────┼────────────┤
│    0    │ '_id' │ '100.0 %' │ 'ObjectID' │
│    1    │ 'a  ' │ '100.0 %' │  'Number'  │
└─────────┴───────┴───────────┴────────────┘
> schema(db.test.aggregate([{ $group: { _id: null, count: { $sum: 1 } } }]));
┌─────────┬─────────┬───────────┬──────────┐
│ (index) │    0    │     1     │    2     │
├─────────┼─────────┼───────────┼──────────┤
│    0    │ '_id  ' │ '100.0 %' │  'Null'  │
│    1    │ 'count' │ '100.0 %' │ 'Number' │
└─────────┴─────────┴───────────┴──────────┘
> schema(db.coll, { verbose: true });
{
  fields: [
    {
      name: '_id',
      // [ ... ]
    },
    {
      path: 'a',
      count: 2,
      types: [
        {
          name: 'Number',
          path: 'a',
          probability: 0.5,
          unique: 1,
          // [ ... ]
        },
        {
          name: 'String',
          bsonType: 'String',
          // [ ... ]
        }
      ],
      total_count: 2,
      type: [ 'Number', 'String' ],
      probability: 1
    }
  ],
  count: 2
}

```
npm package: @mongosh/snippet-llm-command
Description: Provides a llm command to ask for MongoDB query expressions in natural language, using Groq or any other local model (ollama)
Author: Juanan Pereira
Latest version: 0.0.9

# LLM Command Snippet

This snippet adds an `llm` command to mongosh that provides helpful suggestions or recommendations for MongoDB-related tasks. The query results are generated using Groq API by default, with an option to use other models via Ollama.

## Prerequisites

```
export GROQ_API_KEY=gsk_XXXXXXX
mongosh
```

## Usage

After installing the snippet, you can use the `llm` command in your MongoDB shell like this:

```javascript
llm("very briefly, just the command, do not use markdown: in mongosh how to get the collections names of current db?");
```

This will output a possible solution to your query, such as `db.getCollectionNames()`.

```javascript
llm("very briefly, just the command, do not use markdown: in mongosh replace all documents of a collection with property {'set':'llm102'} with the new value {'set':'llm101'} in current db?")
```

This will output a possible solution to your query, such as `db.collection.updateMany({ set: 'llm102' }, { $set: { set: 'llm101' } })`.

You can also specify a different model to use with an optional parameter:
```javascript 
llm("Your query here", { model: "phi3.5" });
```
This will use the specified model (in this case, 'phi3.5') via Ollama instead of the default Groq API.

## Models

By default, the `llm` command uses the Groq API with the 'llama-3.1-70b-versatile' model. You can use other models by specifying them in the optional parameter:

- Groq API (default): No need to specify, just use `llm("Your query")`.
- Ollama models: Specify the model name, e.g., `llm("Your query", { model: "gemini2" })` or `llm("Your query", { model: "phi3.5" })`.

Note: When using Ollama models, make sure you have Ollama running locally on the default port (11434).


## Installation

You can install this snippet using the `snippet` command in mongosh:

```javascript
snippet install llm-command
```

## Troubleshooting

If you get the error:
```
"Error: Cannot find module 'groq-sdk'"
```
then, go to your $USER/.mongodb/mongosh/snippets/node_modules/@juananpe/snippets-llm-command folder
and run `npm install`. Then close and open mongosh again.


## License

This snippet is licensed under the Apache-2.0 license.
npm package: @mongosh/snippet-mock-collection
Description: mockCollection([{ a: 1 }, { a: 2 }]).find({ a: { $gt: 2 } })
Latest version: 1.0.3

# mock-collection

Provide a fake read-only collection based on input documents.

```js
> mockCollection([{ field: 1 },{ field: 2},{ field: 3 }])
> coll.find({ field: {$gt:2} }, { _id: 1 })
[ { _id: ObjectId("6079840f2454d2cd1073ba6c") } ]
> coll.mapReduce(function() { emit('fieldValue', this.field); },
...              function(key, values) { return key + values.join(','); },
...              { out: { inline: 1 } })
{ results: [ { _id: 'fieldValue', value: 'fieldValue1,2,3' } ], ok: 1 }
```
npm package: @mongosh/snippet-spawn-mongod
Description: Spin up a local mongod process
Latest version: 1.0.2

# spawn-mongod

Spin up a local mongod process.

```js
// Copy data from a collection on the current server to a new server:
> const mongod = spawnMongod({ version: 'latest', port: 27097 })
> mongod.waitReady
listening!
> db.coll.find().forEach(doc => mongod.getDB('test').coll.insertOne(doc))
```
npm package: @mongosh/snippet-uuidhelpers
Description: Mongosh snippet containing various small utilities for working with UUIDs.
Latest version: 0.1.2

# uuidhelpers

A new home for the C#/.NET driver's [uuidhelpers.js](https://github.com/mongodb/mongo-csharp-driver/blob/ac2b2a61c6b7a193cf0266dfb8c65f86c2bf7572/uuidhelpers.js).