# MongoDB Command

The MongoDB Command step allows you to execute any MongoDB command using the `db.command` method.

With this step, you can leverage the full power of MongoDB commands to interact with your MongoDB database. You can perform advanced operations, run aggregation pipelines, execute complex queries, and take advantage of specialized features specific to MongoDB.

{% hint style="warning" %}
Make sure to use [MongoDB Extended JSON (v2)](https://www.mongodb.com/docs/manual/reference/mongodb-extended-json/) in your queries to prevent issues with complex data types (for example, *UUID* or *Date*).
{% endhint %}

<figure><img src="/files/YcZNGx8kw9I5PGt00BMA" alt=""><figcaption></figcaption></figure>

## MongoDB command examples

To run a MongoDB command, you simply need to select it in the *Action selection dropdown* and provide the necessary parameters. UI Bakery will then execute the command using the `db.command` method behind the scenes.

In the example below, the `find` command retrieves documents from the *users* collection where the `age` field is greater than or equal to 30. The `projection` parameter specifies that only the `name` and `age` fields should be included in the result.

```js
{
  find: "users",
  filter: { age: { $gte: 30 } },
  projection: { name: 1, age: 1 }
}
```

The **Command Parameters** field in this action step provides a familiar code editor interface allowing you to conveniently interact with the user interface and write JavaScript code, for example:

```js
const minAge = +{{ui.input.value}}

return {
  find: "users",
  filter: { age: { $gte: minAge } },
  projection: { name: 1, age: 1 }
}
```

### Filter by Date

If the MongoDB **Date** property is of the *BSON* type, then in order to be able to filter by Date you should send not the date itself but rather an object with the key `&date` inside the &*lt, \&gt, \&gte* operators. Below is an example of the code you can use:

```javascript
{
 find: "orders",
 filter: {
   "created_at": {
     $gte: {
       $date: "2022-08-11T04:00:00+0400"
     }
   }
 },
   limit: 1000
}
```

### Aggregate

To perform data aggregation, you can use the `aggregate` operation with the following parameters:

```js
{
  aggregate: "users",
  pipeline: [
    { $match: { age: { $gte: 30 } } },
    { $group: { _id: "$status", count: { $sum: 1 } } }
  ],
  cursor: { batchSize: 10 }
}
```

In this example, the aggregation pipeline consists of several stages:&#x20;

* `$match` to filter documents based on the `age` field
* `$group` to group documents by the `status` field and calculate the `count`

### Join and aggregate

You can also use the `aggregate` command in MongoDB to perform complex aggregations on your data by combining multiple stages in a pipeline:

```js
{
  aggregate: "users",
  pipeline: [
    { $match: { age: { $gte: 30 } } },
    { $lookup: { from: "orders", localField: "_id", foreignField: "userId", as: "user_orders" } },
    { $unwind: "$user_orders" },
    { $group: { _id: "$_id", total_orders: { $sum: 1 }, total_amount: { $sum: "$user_orders.amount" } } },
    { $sort: { total_amount: -1 } },
    { $limit: 10 }
  ],
  cursor: { batchSize: 10 }
}
```

In this query, we're performing the following **operations**:

1. `$match` - Filters the documents to include only those where the `age` is greater than or equal to 30.
2. `$lookup` - Joins the *users* collection with the *orders* collection based on the `_id` field of users and the `userId` field of orders. This creates an array called *user\_orders* containing the matching orders for each user.
3. `$unwind` - Deconstructs the *user\_orders* array creating separate documents for each order associated with a user.
4. `$group` - Groups the documents by `_id` (which is the unique identifier of the user) and calculates the total number of orders (`total_orders`) and the total amount of orders (`total_amount`) by summing up the amount field from the *user\_orders* array.
5. `$sort` - Sorts the resulting documents in descending order based on the `total_amount` field.
6. `$limit` - Limits the result to a maximum of 10 documents.

This query performs a *join* and *aggregation* operation to find users aged 30 or above, counts their total number of orders, calculates the total amount of their orders, and sorts the results by the total order amount in descending order. Finally, it limits the result to the top 10 users with the highest total order amount.

### Insert multiple documents

To insert multiple documents into a collection, use the `insertMany` command:

```js
{
  insert: "users",
  documents: [
    { name: "John", age: 30 },
    { name: "Jane", age: 25 }
  ],
  ordered: false
}
```

This example inserts two documents into the collection. Each document specifies the `name` and `age` fields.

The `insert` command allows you to insert one or more documents into a collection. The `ordered` option is set to false to continue inserting the remaining documents even if an error occurs for any individual document.

### Update multiple documents

To update multiple documents in a collection, use the `update` command:

```js
{
  update: "users",
  updates: [
    { q: { age: { $gte: 30 } }, u: { $set: { status: "inactive" } }, multi: true }
  ]
}
```

This example updates all documents in the collection where the `age` is greater or equal to 30. The `$set` operator is used to set the `status` field to *inactive*.

The `update` command allows you to update one or more documents in a collection. The `updates` array contains the update operations, where each operation has:

* the `q` field for the query/filter
* the `u` field for the update
* the `multi` field set to *true* to update multiple documents

### Delete multiple documents

To delete multiple documents from a collection, use the `delete` command:

```js
{
  delete: "users",
  deletes: [
    { q: { status: "inactive" }, limit: 0 }
  ]
}
```

This example deletes all documents from the collection where the `status` field is `inactive`.

The `delete` command allows you to delete one or more documents in a collection. The `deletes` array contains the delete operations, where each operation has:

* the `q` field for the query/filter
* the `limit` field set to `0` to delete all matching documents

### Find one and modify

The `findAndModify` command allows you to find a single document in your collection based on a filter condition and update it:

```js
{
  findAndModify: "users",
  query: { name: "John" },
  update: { $set: { name: "John Doe", age: 40 } },
  new: true
}
```

This operation will find a document in the "users" table with the `name` "John" and update its `age` to 40 and `name` to *John Doe*.

The `findAndModify` command is used to atomically find and modify a document in a collection:

* the `query` field specifies the filter for the document to find
* the `update` field specifies the replacement document
* the `new` option set to `true` returns the modified document

{% hint style="info" %}
UI Bakery supports [MongoDB Extended JSON v2](https://www.mongodb.com/docs/manual/reference/mongodb-extended-json/), so you can use the`$oid` notation. For example, if you need to find one item by **id**, you can do it in the following way:

`{find: 'orders', filter: { id: {$oid: 'required_id'}}}`
{% endhint %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.uibakery.io/reference/working-with-actions/mongodb-command.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
