To handle multiple MongoDb filters in C#, I had wrote below method;
public string MultipleFilters(string collectionName, Dictionary<string, string> dictFilters)
{
var filter = Builders<BsonDocument>.Filter.Eq("", "");
foreach (KeyValuePair<string, string> entry in dictFilters)
{
filter = filter & Builders<BsonDocument>.Filter.Eq(entry.Key, entry.Value);
}
var collection = this.database.GetCollection<BsonDocument>(collectionName);
var document = collection.Find(filter).First();
return document.ToJson();
}
But it throws the error:
System.InvalidOperationException: 'Sequence contains no elements'
Builders<BsonDocument>.Filter.Eq("", "")is a valid MongoDB filter which tries to find a document with an empty key and empty value (example),it's better to use
Builders<BsonDocument>.Filter.Emptyinstead.Also you're running
.First()on after.Find()method so you're assuming that there's always at least one value. That's fine if you wantSequence contains no elementsto be thrown when something goes wrong however you can try to handle that more gracefully by using.FirstOrDefault()