Home > front end >  Is there a way to break this 'project' portion of a pipeline down into smaller pieces?
Is there a way to break this 'project' portion of a pipeline down into smaller pieces?

Time:10-29

I have this mongo playground

I would like to break down this project into small chunks so I can see what's happening in the pipeline

    "$project": {
      "people": {
        "$map": {
          "input": "$peopleLookup",
          "as": "tempPeople",
          "in": {
            "$mergeObjects": [
              "$$tempPeople",
              {
                "userType": {
                  "$first": {
                    "$filter": {
                      "input": "$userTypeLookup",
                      "cond": {
                        "$eq": [
                          "$$tempPeople.REF_UserType",
                          "$$this._id"
                        ]
                      }
                    }
                  }
                }
              }
            ]
          }
        }
      }
    }

CodePudding user response:

I don't think there is a general way to break down aggregation stage(s). But for your specific case, your query seems to be trying to perform a common 'lookup-then-combine' operation. The query performs 2 lookups to users and usertypes collections and 'links' up the lookup results together by ids inside.

An arguably more comprehensible way to perform the same behaviour would be:

Precaution: You can see there is a sub-pipeline inside sub-pipeline. Usually it would be a bad idea as it would make the pipeline complicated and hinder readability. However for your case, it may be ok as we can keep it simple to 1 single $limit stage only. We avoid excessive $lookup to gain some performance.

db.workoutDetailSchema.aggregate([
  {
    "$lookup": {
      "from": "users",
      "localField": "REF_Users",
      "foreignField": "_id",
      "pipeline": [
        {
          "$lookup": {
            "from": "usertypes",
            "localField": "REF_UserType",
            "foreignField": "_id",
            "pipeline": [
              {
                $limit: 1
              }
            ],
            "as": "userType"
          }
        },
        {
          "$unwind": "$userType"
        }
      ],
      "as": "people"
    }
  }
])

Mongo Playground (some wrangling stages are omitted to keep it simple for demo purpose)

You can see a sub-pipeline is used to perform another lookup and handle the 'linkage'. Potentially it could be more performant, as it doesn't need to iterate through the lookup arrays.

  • Related