Search code examples
c#mongodbmongodb-.net-driver

How to get values of one field in array in MongoDB Driver for C#


I have the classes:

public class Whole
{
  public ObjectId Id { get; set; }
  public string NeededField { get; set; }
  public List<Detail> Details { get; set; }
  public string SomeUnnecesaryField { get; set; } 
}

public class Detail
{
  public string NeededField { get; set; }
  public string NotNeededField { get; set; }
}

[BsonNoId]
[BsonIgnoreExtraElements]
public class MyNeededInformations
{
  public string NeededField { get; set; }
  [BsonElement("Details.NeededField")]
  public List<string> DetailsNeededFields { get; set; }
}

And I trying to obtain it with projection:

var filter = someFilter;
var projection = Builders<Whole>.Projection
  .Include(w => w.NeededField)
  .Include(w => w.Details)
  .Exclude("_id");
return Collection
  .Find(filter)
  .Project(projection)
  .As<MyNeededInformations>()
  .ToList();

And I receive DetailsNeededFields as empty list every time. I want to have list of strings like with standard aggeregate:

db.collection.aggregate([
  {$match: someFilter},
  {$project: {"_id": 0, "NeededField": 1, "DetailsNeededFields": "$Details.NeededField"}}
])

Solution

  • can be achieved easily with the AsQueryable interface like so:

    var results = await collection
        .AsQueryable()
        .Where(_ => true)
        .Select(w => new MyNeededInformations
        {
            NeededField = w.NeededField,
            DetailsNeededFields = (List<string>)w.Details.Select(d => d.NeededField)
        })
        .ToListAsync();