Search code examples
c#.netmongodbmongodb-querymongodb-.net-driver

translating mongo query to C# by using Filter


Is there any way to use Filters in C# and translate this mongo query?

{'EmailData.Attachments.Files': {$all: [{Name: 'a.txt'},{Name: 'b.txt'},{Name:'c.txt'}], $size: 3}}

my data model is like:

{
"_id": ObjectId("5f0a9c07b001406068c073c1"), 

"EmailData" : [
    {

        "Attachments" : {

            "Files" : [
                {
                    "Name" : "a.txt" 

                }, 
                {
                    "Name" : "b.txt"
                }, 
                {
                    "Name" : "c.txt"

                }
            ]
        }
    }
]
}

I have something like this in my mind:

    var Filter =
                Builders<EmailEntity>.Filter.All(s => s.EmailData????);

or something like:

var Filter =
                Builders<EmailEntity>.Filter.ElemMatch(s => s.EmailData???)

I was wondering is there any way in the above filter to use All inside ElemMatch?


Solution

  • The difficulty here is that EmailData.Attachments.Files is an array within another array so C# compiler will get lost when you try to use Expression Trees.

    Thankfully there's another approach when you need to define a field using MongoDB .NET driver. You can take advantage of StringFieldDefinition<T> class.

    Try:

    var files = new[] { new FileData(){ Name = "a.txt"}, new FileData() { Name = "b.txt" }, new FileData() { Name = "c.txt" } };
    
    FieldDefinition<EmailEntity> fieldDef = new StringFieldDefinition<EmailEntity>("EmailData.Attachments.Files");
    
    var filter = Builders<EmailEntity>.Filter.And(
                     Builders<EmailEntity>.Filter.All(fieldDef, files),
                     Builders<EmailEntity>.Filter.Size(fieldDef, 3));
    
    var result= collection.Find(filter).ToList();