MongoDB how to check for existence

Viewed 36174

I would like to know how can I check the existence of an object with mongoDB and C#.

I've found a way to do it but I had to use Linq thanks to Any() method, but I'd like to know if it's possible to do it without Linq ?

database.GetCollection<ApplicationViewModel>("Applications").Find(Query.EQ("Name", applicationName)).Any()

Thanks guys!

7 Answers

The way to check for existence in the 2.x version of the driver is:

bool exists = collection.Find(_ => _.Name == applicationName).Any();

Or asynchronously:

bool exists = await collection.Find(_ => _.Name == applicationName).AnyAsync();;

From this article we read:

However, it is significantly faster to use find() + limit() because findOne() will always read + return the document if it exists. find() just returns a cursor (or not) and only reads the data if you iterate through the cursor.

That means that using something like:

database.GetCollection<ApplicationViewModel>("Applications").Find(Query.EQ("Name", applicationName)).Limit(1)

will probably be fastest.

Use CountDocument method:

long count = await items.CountDocumentsAsync(yourFilter, null, cancellationToken);

if(count > 0)
{
    //document exists
}
Related