Here's the code:
ProjectionDefinition<Accountant> projDefAccountant = Builders<Accountant>.Projection
.Include(x => x.Id)
.Include(x => x.Name);
ProjectionDefinition<Client> projDefClient = Builders<Client>.Projection
.Include(c => c.Name)
.Include(c => c.Address)
.Include(c => c.Occupation);
IMongoCollection<Accountant> collection = mongoDatabase.GetCollection<Accountant>("accountants");
IMongoCollection<Client> foreignCollection = mongoDatabase.GetCollection<Client>("clients");
var results = collection.Aggregate()
.Project<Accountant>(projDefAccountant)
.Lookup<Accountant, Client, Accountant>(
foreignCollection: foreignCollection,
localField: ac => ac.BestClientsIds,
foreignField: c => c.Id,
@as: ac => ac.MyClients
).ToList().AsQueryable();
I'm able to use the first projection "projDefAccountant" to limit what fields I want out of the "accountants" collection. Is there a way to enforce the "projDefClient" projection on the joined "clients" collection so that the join doesn't return all the fields but only those specified in the "projDefClient"? Thx.
You can use $lookup with custom pipeline and your aggregation could look like this:
Mongo Playground
In C# there's one overloaded version of
.Lookupwhich allows you to run that method in an almost strongly-typed way. Here's the signature:You can modify
projDefAccountantso that it includesBestClientsIdsfield:Then it's easier to specify
letand$matchphases asBsonDocumenthowever the rest stays strongly-typed: