One to Many relationship join and project

Hi @MWD_Wajih_N_A,

The following aggregation lookup can do the requested… Its important to note that using a lookup can potentially have performance overhead and we suggest to design the schema to avoid lookups as much as possible.

db.collectionB.aggregate([{$lookup: {
  from: 'collectionA',
  localField: 'a_id',
  foreignField: 'b_id',
  as: 'lookup'
}}, {$project: {
  "name" : { $first : "$lookup.name" },
  "age"  : { $first : "$lookup.age" },
  FeeAmount : 1,
  Date : 1,
  PaidAmount : 1,
  availableLimitAmount : 1
}}])

RESULT:

{ _id: ObjectId("6061d50144567725448f109b"),
  FeeAmount: 800000,
  Date: '2021-10-29T00:00:00.000+04:00',
  PaidAmount: 200000,
  name: 'xyz',
  age: 5 }
{ _id: ObjectId("6061d50144567725448f109c"),
  FeeAmount: 90,
  Date: '2021-10-29T00:00:00.000+04:00',
  PaidAmount: 20,
  name: 'xyz',
  age: 5 }

Best regards,
Pavel

1 Like