0

I have written this aggregate and it works fine

db.ParcelStatus.aggregate([{
     {
         $lookup: {
             from: "Parcel",
             localField: "parcelId",
             foreignField: "_id",
             as: "parcel"
         }
     },
     {
         $unwind: {
             path: "$parcel",
             preserveNullAndEmptyArrays: true
         }
     },
     {
         $lookup: {
             from: "ParcelStatus",
             localField: "parcel._id",
             foreignField: "parcelId",
             as: "parcel.parcelStatuses"
         }
     },
     {
         $lookup: {
             from: "Customer",
             localField: "parcel.customerData.customerId",
             foreignField: "_id",
             as: "parcel.customerData.customer"
         }
     },
     {
         $unwind: "$parcel.customerData.customer"
     }
 ])

Now in ParcelStatus array that is INCLUDED inside PARCEL object i need to check that

if(parcel.ParcelStatus.includes((x) => x.statusRepositoryId === 'ID's from frontend')
//then run $match on root against statusRepositoryId === 'SPECIFIC STATIC ID'

I don't know how i can do that inside aggregate. Your help will be much appreciated

2
  • You may post the document structure on which to apply the condition. Commented Jun 18, 2020 at 11:01
  • @prasad_ you can consider this simple object in parcelStatus {id: '_id', statusRepositoryId:'statusId', parcelId:'parcel id'} Commented Jun 18, 2020 at 12:10

1 Answer 1

1

Just add this $match stage:

{
    $match: {
        "parcel.parcelStatuses.statusRepositoryId": {$in: idArrayFromClient}
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

this match stage needs to be inside lookup or in start?
Hey tom, thanks agains for your answer but i am unable to figure out where i need to fix this stage, would you be kind enough to write full aggregate? also is this a right way parcel.parcelStatuses.statusRepositoryId? parcelStatuses is array and not object so i am not sure if i can access statusrepositoryId inside parcelStatuses array like this
Just add this stage to the very end. (or after the lookup that retrieves the repositroy id). The syntax is correct, it's the behaviour of Mongo's dot notation: docs.mongodb.com/manual/core/document/#dot-notation

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.