Return total documents from a Mongodb Collection?

Asked

Viewed 279 times

0

I made a api in C# and it’s the first time I’ve used Mongo as a bank and on a route I need to get the total records I have on my Collection.

I tried several ways but could not find a way to return a number int and doing some research I found this way but it returns me a long kind.

private async Task<long> CountVacancyAsync()
    => await _collection.Find(x => x.Activy.Equals(true) || x.Activy.Equals(false))
                        .CountDocumentsAsync();

Is there any more correct way to return the total records and needs to be the same type long?

1 answer

0


The Package driver created for Mongodb only offers a method to count the amount of documents from a collection with the return type long, was thus written and so should be used.

Code:

Task<long> CountDocumentsAsync(
    FilterDefinition<TDocument> filter,
    CountOptions options = null,
    CancellationToken cancellationToken = null
)

But maybe I can use the method AsQueryable() of the interface IMongoQueryable<T> (which is the for Mongodb) and in that case may have the result for the type int, example:

int count = _collection.AsQueryable().Count();

Another problem in your code is this method find which is unnecessary in this code, can write in a more summarized way:

private async Task<long> CountVacancyAsync() => await _collection.CountDocumentsAsync();

Note: only type filters when necessary, because, your question auto cancels bringing all, then it is not necessary to make a filter.

If you want to use it anyway (as already mentioned is unnecessary, but, a way to exemplify how you could write) use so

.find(new BsonDocument())

References:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.