Search code examples
c#mongodbmongodb-.net-drivermongodb.driver

Multiple MongoDb filters in C#


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'

Solution

  • 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.Empty instead.

    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 want Sequence contains no elements to be thrown when something goes wrong however you can try to handle that more gracefully by using .FirstOrDefault()