captain sparrow
captain sparrow

Reputation: 81

Join multiple collections using Aggregations with conditions

i have 3 collections like this

  ModelA : 

  {
      _id :ObjectId("60d2cd964200b320e7dc5c04"),
      name : 'Item 1'
  }


  ModelB : 

  {
      _id :ObjectId("60e3c8e0748d2a18476ceb6f"),
      modelA : ObjectId("60d2cd964200b320e7dc5c04"),
      field1 : 'field1 item A',
      field2 : 'field2 item B',
  }


  ModelC : 

  {
      _id :ObjectId("60e3c8e0748d2a18476ceb70"),
      modelB : ObjectId("60e3c8e0748d2a18476ceb6f"),
      status : 'finish'
  }

i want to fetch data all these collections where the ModelA name is 'Item 1' and ModelC status is equal 'Finish', how can i join these 3 collections using Aggregations ?

Upvotes: 0

Views: 54

Answers (1)

Duy Quoc
Duy Quoc

Reputation: 181

You can put multiple $lookup stages to join multiple collections, so you could use a query like this:

db.ModelA.aggregate([
   {
      $lookup:{
         from:"ModelB",
         localField:"_id",
         foreignField:"modelA",
         as:"modelB"
      }
   },
   {
      $unwind:"$modelB"
   },
   {
      $lookup:{
         from:"modelC",
         localField:"ModelB._id",
         foreignField:"modelB",
         as:"modelC"
      }
   },
   {
      $unwind:"$modelC"
   },
   {
      $match: {
         name: "Item 1",
         "modelC.status": "finish"
      }
   },
   { // disable this stage if you want to get all fields of 3 collections or modify it with the output that you want
      $project:{
         "name": 1,
         "status": "$modelC.status"
      }
   }
]);

Upvotes: 1

Related Questions