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

Project a single array item mongodb C#


I have the following json

{
   "name":"Student",
    "Classes" : ["Chemistry","Math","Algebra"]
 }

and the following poco

public class Studen
{
     public string Name {get;set;}
     public string[] Classes {get; set;}
}

I want to query a specific student that takes a specific class (say Math), and the poco to have a single item in the array which is the "Math" string


Solution

  • if your collection is a variable collection:

    collection.Find(x => x.Classes.Contains("Math"))
              .Project(s => 
                       new Student {
                            Name = s.Name,
                            Classes = s.Classes.Where(c=>c=="Math").ToArray()})
             .ToList();