Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB how to check for existence

Tags:

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!

like image 294
John Avatar asked Jun 20 '11 12:06

John


People also ask

What is the command to check existence of collection in MongoDB?

If the database is not present, MongoDB will automatically create one. The collectionExists method can be used to check whether a collection is present or not: MongoClient mongoClient = new MongoClient("localhost", 27017); DB db = mongoClient.

What is exist in MongoDB?

When <boolean> is true, $exists matches the documents that contain the field, including documents where the field value is null . If <boolean> is false, the query returns only the documents that do not contain the field. [ 1] MongoDB $exists does not correspond to SQL operator exists .

Does MongoDB Create collection if not exists?

If a collection does not exist, MongoDB creates the collection when you first store data for that collection. You can also explicitly create a collection with various options, such as setting the maximum size or the documentation validation rules.

What does find () do in MongoDB?

Find() Method. In MongoDB, find() method is used to select documents in a collection and return a cursor to the selected documents.


1 Answers

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));
like image 187
Andrew Orsich Avatar answered Sep 24 '22 20:09

Andrew Orsich