Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

345
Views
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"}}
])
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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();
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!