Gui Gui - 1 year ago 146
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!

Answer Source

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));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download