MongoDB C# Methode to search for a Document (Document of Type T)

Viewed 118

I did write a CRUD App for MongoDB with C#. I try to make it as universal as possible (atleast as good as I could for me).

So I used a Type T as the type for the document.

        public List<T> SearchDocument<T>(string collection, string fieldName, string fieldValue)
    {
        var _collection = db.GetCollection<T>(collection);
        var filter = Builders<T>.Filter.Eq(fieldName, fieldValue);
        var result = _collection.Find(filter).ToList();
        return result;
    }

That methode works and finds a Document in a MongoDb that has a given Value of a given Field. What I don't know is how to make the Type of the "string filedValue" also type T so to speak.

How can I make the Type of the fieldValue also generic even so I already used T ?

public List<T> SearchDocument<T>(string collection, string fieldName, string fieldValue)

should be somthing like

public List<T> SearchDocument<T>(string collection, string fieldName, <an other T>  fieldValue)

Where as the second T is a totaly different Typ as the first T, I did just write it here so I hope somebody can understand what I mean. I know it can't be the same T as in the SearchDoc

Thank You :) for Input

1 Answers

You need second generic type TField:

public List<T> SearchDocument<T, TField>(string collection, string fieldName, TField fieldValue)
{
    var _collection = db.GetCollection<T>(collection);
    var filter = Builders<T>.Filter.Eq<TField>(fieldName, fieldValue);
    var result = _collection.Find(filter).ToList();
    return result;
}
Related