* Gets the number of documents matching the filter. * For a fast count of the total documents in a collection see {@link Collection#estimatedDocumentCount| estimatedDocumentCount}. * * Due to countDocuments using the $match aggregation pipeline stage, certain query operators cannot be used
(
filter: Filter<TSchema> = {},
options: CountDocumentsOptions & Abortable = {}
)
| 829 | * @see https://www.mongodb.com/docs/manual/reference/operator/query/centerSphere/#op._S_centerSphere |
| 830 | */ |
| 831 | async countDocuments( |
| 832 | filter: Filter<TSchema> = {}, |
| 833 | options: CountDocumentsOptions & Abortable = {} |
| 834 | ): Promise<number> { |
| 835 | const pipeline = []; |
| 836 | pipeline.push({ $match: filter }); |
| 837 | |
| 838 | if (typeof options.skip === 'number') { |
| 839 | pipeline.push({ $skip: options.skip }); |
| 840 | } |
| 841 | |
| 842 | if (typeof options.limit === 'number') { |
| 843 | pipeline.push({ $limit: options.limit }); |
| 844 | } |
| 845 | |
| 846 | pipeline.push({ $group: { _id: 1, n: { $sum: 1 } } }); |
| 847 | |
| 848 | const cursor = this.aggregate<{ n: number }>(pipeline, options); |
| 849 | const doc = await cursor.next(); |
| 850 | await cursor.close(); |
| 851 | return doc?.n ?? 0; |
| 852 | } |
| 853 | |
| 854 | /** |
| 855 | * The distinct command returns a list of distinct values for the given key across a collection. |