Skip to content

Commit ebd61d1

Browse files
authored
feat: expose countDocuments in mongodb (#10314)
1 parent e296063 commit ebd61d1

File tree

3 files changed

+36
-0
lines changed

3 files changed

+36
-0
lines changed

docs/mongodb.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -284,6 +284,10 @@ Perform a bulkWrite operation without a fluent API.
284284

285285
Count number of matching documents in the db to a query.
286286

287+
### `countDocuments`
288+
289+
Count number of matching documents in the db to a query.
290+
287291
#### `createCollectionIndex`
288292

289293
Creates an index on the db and collection.

src/entity-manager/MongoEntityManager.ts

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@ import {
5454
IndexInformationOptions,
5555
ObjectId,
5656
FilterOperators,
57+
CountDocumentsOptions,
5758
} from "../driver/mongodb/typings"
5859
import { DataSource } from "../data-source/DataSource"
5960
import { MongoFindManyOptions } from "../find-options/mongodb/MongoFindManyOptions"
@@ -499,6 +500,22 @@ export class MongoEntityManager extends EntityManager {
499500
return this.mongoQueryRunner.count(metadata.tableName, query, options)
500501
}
501502

503+
/**
504+
* Count number of matching documents in the db to a query.
505+
*/
506+
countDocuments<Entity>(
507+
entityClassOrName: EntityTarget<Entity>,
508+
query: Filter<Document> = {},
509+
options: CountDocumentsOptions = {},
510+
): Promise<number> {
511+
const metadata = this.connection.getMetadata(entityClassOrName)
512+
return this.mongoQueryRunner.countDocuments(
513+
metadata.tableName,
514+
query,
515+
options,
516+
)
517+
}
518+
502519
/**
503520
* Count number of matching documents in the db to a query.
504521
*/

src/repository/MongoRepository.ts

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ import {
4343
UpdateFilter,
4444
UpdateOptions,
4545
UpdateResult,
46+
CountDocumentsOptions,
4647
} from "../driver/mongodb/typings"
4748
import { FindManyOptions } from "../find-options/FindManyOptions"
4849

@@ -244,6 +245,20 @@ export class MongoRepository<
244245
return this.manager.count(this.metadata.target, query || {}, options)
245246
}
246247

248+
/**
249+
* Count number of matching documents in the db to a query.
250+
*/
251+
countDocuments(
252+
query?: ObjectLiteral,
253+
options?: CountDocumentsOptions,
254+
): Promise<number> {
255+
return this.manager.countDocuments(
256+
this.metadata.target,
257+
query || {},
258+
options,
259+
)
260+
}
261+
247262
/**
248263
* Count number of matching documents in the db to a query.
249264
*/

0 commit comments

Comments
 (0)