Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
102 changes: 102 additions & 0 deletions api-reference/operators/aggregation/$count.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
---
title: $count

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Three issues — the first may make the rest moot

This page duplicates accumulators/$count.md (392 lines), which already documents the $count stage, including the same $unwind + $count example. It's the only duplicate title: in the repo, and with no navigation.yml both pages will surface. They also contradict each other on collection size — 5 here vs 41501 there, corroborated by $collstats.md:164 and $bucket.md:176. → Maintainer call: drop this page, or relocate the existing one.

Line 93 — Example 3 unwinds promotionEvents, which is absent from this page's own sample document (lines 31-47). Fix the sample, not the query. Same defect at $project.md:93.

Line 101 — the $group equivalence is false on empty input: $count builds an ungrouped aggregate (always one row), $group a real GROUP BY (zero rows). This contradicts line 100, which is the correct one. Source read.

description: The $count stage returns a count of the number of documents at this stage of the aggregation pipeline.
type: operators
category: aggregation
---

# $count

The `$count` stage passes a document to the next stage that contains a count of the number of documents input to the stage. This is useful for getting the total number of documents that match earlier pipeline stages.

## Syntax

```javascript
{
$count: <string>
}
```

## Parameters

| Parameter | Description |
| --- | --- |
| **`string`** | Required. The name of the output field which has the count as its value. Must be a non-empty string, must not start with `$`, and must not contain the `.` character. |

## Examples

Consider this sample document from the stores collection.

```json
{
"_id": "2cf3f885-9962-4b67-a172-aa9039e9ae2f",
"name": "First Up Consultants | Bed and Bath Center - South Amir",
"location": {
"lat": 60.7954,
"lon": -142.0012
},
"staff": {
"totalStaff": {
"fullTime": 18,
"partTime": 17
}
},
"sales": {
"totalSales": 37701
}
}
```

### Example 1: Count all documents

Count the total number of documents in the collection:

```javascript
db.stores.aggregate([
{ $count: "totalStores" }
])
```

This query returns:

```json
[
{ "totalStores": 5 }
]
```

### Example 2: Count documents after filtering

Count stores that have more than 10 full-time staff:

```javascript
db.stores.aggregate([
{ $match: { "staff.totalStaff.fullTime": { $gt: 10 } } },
{ $count: "highStaffStores" }
])
```

This query returns:

```json
[
{ "highStaffStores": 3 }
]
```

### Example 3: Count with $unwind

Count the total number of promotion events across all stores:

```javascript
db.stores.aggregate([
{ $unwind: "$promotionEvents" },
{ $count: "totalPromotionEvents" }
])
```

## Key Takeaways

- **Single output document** — `$count` always returns exactly one document with a single field
- **Close to, but not the same as, `$group`** — `{ $count: "total" }` resembles `{ $group: { _id: null, total: { $sum: 1 } } }` followed by `{ $project: { _id: 0 } }`, and the two agree whenever any document reaches the stage. They diverge on empty input: `$count` builds an ungrouped aggregate, which always produces a row, so it returns `{ "total": 0 }`, while `$group` performs a real grouping and returns nothing at all. Use `$count` when a downstream stage depends on always receiving a document.
- **Field name restrictions** — the output field name must be non-empty, cannot start with `$`, and cannot contain `.`
77 changes: 77 additions & 0 deletions api-reference/operators/aggregation/$currentop.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
---
title: $currentOp
description: The $currentOp stage returns information on active and queued operations for the database.
type: operators
category: aggregation
---

# $currentOp

The `$currentOp` stage returns a stream of documents containing information on active and queued operations for the database instance. This stage must be the first stage in the pipeline and is run on the `admin` database.

## Syntax

```javascript
db.adminCommand({
aggregate: 1,
pipeline: [
{
$currentOp: {
allUsers: <boolean>,
idleConnections: <boolean>,
idleCursors: <boolean>,
idleSessions: <boolean>,
localOps: <boolean>
}
}
],
cursor: {}
})
```

## Parameters

| Parameter | Description |
| --- | --- |
| **`allUsers`** | Optional. Boolean. If `true`, reports operations for all users. Default: `false`. |
| **`idleConnections`** | Optional. Boolean. If `true`, reports on idle connections. Default: `false`. |
| **`idleCursors`** | Optional. Boolean. If `true`, reports on idle cursors. Default: `false`. |
| **`idleSessions`** | Optional. Boolean. If `true`, reports on idle sessions. Default: `false`. |
| **`localOps`** | Optional. Boolean. If `true`, reports operations running locally on the current instance. Default: `false`. |

## Examples

### Example 1: List active operations

Return all currently active operations:

```javascript
db.adminCommand({
aggregate: 1,
pipeline: [
{ $currentOp: { allUsers: true } }
],
cursor: {}
})
```

### Example 2: Filter active operations

Return active operations for a specific database, combined with `$match`:

```javascript
db.adminCommand({
aggregate: 1,
pipeline: [
{ $currentOp: { allUsers: true } },
{ $match: { "ns": /^mydb\./ } }
],
cursor: {}
})
```

## Key Takeaways

- **Must be first stage** — `$currentOp` must be the first stage in the aggregation pipeline
- **Admin database only** — this stage must be run against the `admin` database using `db.adminCommand()`
- **Collection-agnostic** — does not operate on a specific collection
136 changes: 136 additions & 0 deletions api-reference/operators/aggregation/$replaceroot.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
---
title: $replaceRoot
description: The $replaceRoot stage replaces the input document with the specified document.
type: operators
category: aggregation
---

# $replaceRoot

The `$replaceRoot` stage replaces the input document with the specified document. The operation replaces all existing fields in the input document, including the `_id` field. This is useful for promoting an embedded document to the top level.

## Syntax

```javascript
{
$replaceRoot: {
newRoot: <expression>
}
}
```

## Parameters

| Parameter | Description |
| --- | --- |
| **`newRoot`** | Required. A document expression that resolves to a document. The expression can be any valid expression that resolves to a document, such as a field path to an embedded document, a `$mergeObjects` expression, or a literal document. |

## Examples

Consider this sample document from the stores collection.

```json
{
"_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4",
"name": "First Up Consultants | Beverage Shop - Satterfieldmouth",
"location": {
"lat": -89.2384,
"lon": -46.4012
},
"staff": {
"totalStaff": {
"fullTime": 8,
"partTime": 20
}
},
"sales": {
"totalSales": 75670,
"salesByCategory": [
{ "categoryName": "Wine Accessories", "totalSales": 34440 }
]
}
}
```

### Example 1: Promote an embedded document

Promote the `staff.totalStaff` subdocument to the top level:

```javascript
db.stores.aggregate([
{ $replaceRoot: { newRoot: "$staff.totalStaff" } },
{ $limit: 2 }
])
```

This query returns:

```json
[
{ "fullTime": 8, "partTime": 20 }
]
```

### Example 2: Use $mergeObjects to combine fields

Merge the staff subdocument with additional top-level fields:

```javascript
db.stores.aggregate([
{
$replaceRoot: {
newRoot: {
$mergeObjects: [
"$staff.totalStaff",
{ storeName: "$name", totalSales: "$sales.totalSales" }
]
}
}
},
{ $limit: 2 }
])
```

This query returns:

```json
[
{
"fullTime": 8,
"partTime": 20,
"storeName": "First Up Consultants | Beverage Shop - Satterfieldmouth",
"totalSales": 75670
}
]
```

### Example 3: Replace root after $unwind

Extract individual sales categories as top-level documents:

```javascript
db.stores.aggregate([
{ $unwind: "$sales.salesByCategory" },
{
$replaceRoot: {
newRoot: {
$mergeObjects: [
"$sales.salesByCategory",
{ storeName: "$name" }
]
}
}
},
{ $limit: 3 }
])
```

## Limitations

- If `newRoot` evaluates to a missing value or a non-document type, the operation errors

## Key Takeaways

- **Replaces the entire document** — the output document is the evaluated `newRoot` expression
- **`$replaceWith` is an alias** — `{ $replaceWith: <expression> }` is shorthand for `{ $replaceRoot: { newRoot: <expression> } }`
- **Combine with `$mergeObjects`** — use `$mergeObjects` to preserve fields from the original document while promoting an embedded document
Loading