MongoDB how to check for existence

John picture John · Jun 20, 2011 · Viewed 28.1k times · Source

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!

Answer

Andrew Orsich picture Andrew Orsich · Jun 20, 2011

Use $count operator to avoid memory issues, it not loading documents from database into memory:

int count = items.FindAs<LedgerDocument>(Query.EQ("name", appName)).Count();

if(count > 0)
{
   //then doc exists
}

Operator $exists in mongodb can be used to identfy that some field exists in a document, but you can't pass query to it:

database.GetCollection<ApplicationViewModel>("Applications")
                  .Find(Query.Exists("Name", true));