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!
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.
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 .
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.
Find() Method. In MongoDB, find() method is used to select documents in a collection and return a cursor to the selected documents.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With