harshit kohli
harshit kohli

Reputation: 302

how to reduce unnecessary unwind stages from aggregation pipeline

Like if i'm applying many lookup stages in aggregation pipeline and each lookup is followed by an unwind(just to covert into object) first question does it affect query performance? and if yes how to do that in optimised manner

Note: all lookup's will return only one object

For Ex:

xyz.aggregate([
{ $lookup:{ ----}} //first lookup
{$unwind :{----}} //first unwind
{ $lookup:{ ----}} //second lookup
{$unwind :{----}} //second unwind
{ $lookup:{ ----}} //third lookup
{$unwind :{----}} //third unwind
{ $lookup:{ ----}} //fourth lookup
{$unwind :{----}} //fourth unwind
])

Upvotes: 1

Views: 570

Answers (1)

Lahori
Lahori

Reputation: 1091

In reference to comments, here is advanced $lookup:

$lookup: {
        from: 'accounts',
        let: { "localAccountField": "$account" },
        pipeline: [
          {
            $match: {
              $expr: {
                $eq: ["$_id", "$$localAccountField"]
              }
            }
          },
          {
            $project: {
              _id: 1,
              user: 1
            }
          },
          {
            $lookup: {
              from: 'users',
              let: { 'localUserField': "$user" },
              pipeline: [
                {
                  $match: {
                    $expr: {
                      $eq: ["$_id", "$$localUserField"]
                    }
                  }
                },
                {
                  $project: {
                    _id: 1,
                    username: "$uid",
                    phone:"$phoneNumber",
                    email: "$email.add",
                    name: {
                      $concat: [
                        "$profile.name.first",
                        ' ',
                        "$profile.name.last"
                      ]
                    },
                  }
                }
              ],
              as: "users"
            }
          },
          {
            $lookup: {
              from: 'documents',
              let: { 'localDocumentField': "$user" },
              pipeline: [
                {
                  $match: {
                    $expr: {
                      $eq: ["$user", "$$localDocumentField"]
                    },
                    status:"verified",
                    "properties.expirydate": { $exists: true, $ne: "" },
                    name: "idcard"
                  }
                },
                {
                  $project: {
                    _id: 0,
                    cnic: "$properties.number"
                  }
                }
              ],
              as: "documents"
            }
          }
        ],
        as: 'account'
      }

Upvotes: 1

Related Questions