Gui Gui - 6 months ago 70
C# Question

MongoDB how to check for existence

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!


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:

                  .Find(Query.Exists("Name", true));