How to count all documents in a collection using mongodb driver?

Priya
Priya
1182 Points
33 Posts

How to count all documents in a collection using mongodb driver? Here I'm trying following but it's erroring:

var mongoCollection = _mongoDBService.GetCollection<collectionObject>(COLLECTION_NAME);
var count = await mongoCollection.CountDocumentsAsync();
Views: 286
Total Answered: 1
Total Marked As Answer: 0
Posted On: 07-Aug-2023 04:19

Share:   fb twitter linkedin
Answers
beginer
beginer
1544 Points
52 Posts
         

Yes, it's need to pass one mandatory argument:

        //
        // Summary:
        //     Counts the number of documents in the collection. For a fast estimate of the
        //     total documents in a collection see .
        //
        // Parameters:
        //   filter:
        //     The filter.
        //
        //   options:
        //     The options.
        //
        //   cancellationToken:
        //     The cancellation token.
        //
        // Returns:
        //     The number of documents in the collection.
        //
        // Remarks:
        //     Note: when migrating from CountAsync to CountDocumentsAsync the following query
        //     operations must be replaced:
        //     +-------------+--------------------------------+
        //     | Operator    | Replacement                    |
        //     +=============+================================+
        //     | $where      |  $expr                         |
        //     +-------------+--------------------------------+
        //     | $near       |  $geoWithin with $center       |
        //     +-------------+--------------------------------+
        //     | $nearSphere |  $geoWithin with $centerSphere |
        //     +-------------+--------------------------------+
        Task<long> CountDocumentsAsync(FilterDefinition<TDocument> filter, CountOptions options = null, CancellationToken cancellationToken = default(CancellationToken));

Use as:

var count = await mongoCollection.CountDocumentsAsync(x => x.created >= DateTime.UtcNow.Date);
Posted On: 07-Aug-2023 22:03
 Log In to Chat