0

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?

1 Answer 1

1

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();
Sign up to request clarification or add additional context in comments.

1 Comment

It is very interesting for me to know about StringFieldDefinition, thank you for that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.