use('test_FreePlanet');

let passo1 =
[
  {
    $lookup: {
      from: "circuits",
      as: "circuit",
      let: {
        circuitname: "Riso Rovigo",
        idapp: "$idapp",
      },
      pipeline: [
        {
          $match: {
            $expr: {
              $and: [
                {
                  $eq: [
                    "$name",
                    "$$circuitname",
                  ],
                },
                {
                  $eq: [
                    "$idapp",
                    "$$idapp",
                  ],
                },
              ],
            },
          },
        },
      ],
    },
  },

];

let passo1c = [
  {
    $match: {
      $expr: {
        $eq: [
          "$_id",
          "633ed3454b03da33f944da14",
        ],
      },
    },
  },

];

let passo2 = [
  {
    $project: {
      name: 1,
      'req_users': 1,
    },
  },

];

let passo2b = [
  {
    $lookup: {
      from: "users",
      localField: "req_users.username",
      foreignField: "username",
      as: "user",
    },
  },
  {
    $replaceRoot: {
      newRoot: {
        $mergeObjects: [
          {
            $arrayElemAt: [
              "$user",
              0,
            ],
          },
          "$$ROOT",
        ],
      },
    },
  },
  {
    $project: {
      "user.idapp": 1,
      "user.username": 1,
      "user.profile.img": 1,
      "user.profile.qualifica": 1,
    },
  },
  {
    $unwind: "$user",
  },
  {
    $match: {
      $and: [
        {
          "user.idapp": "13",
        },
      ],
    },
  },
  {
    $replaceRoot: {
      newRoot: "$user",
    },
  },
  {
    $match: {
      $and: [
        {
          $or: [
            {
              visibility: {
                $nin: [
                  2,
                ],
              },
            },
            {
              createdBy: {
                $eq: "paoloar77",
              },
            },
          ],
        },
      ],
    },
  },
  {
    $group: {
      _id: null,
      count: {
        $sum: 1,
      },
      results: {
        $push: "$$ROOT",
      },
    },
  },
  {
    $project: {
      count: 1,
      rows: {
        $slice: [
          "$results",
          0,
          10,
        ],
      },
    },
  },
];


let passo3 = [
];


let aggregation = [];

let test = false;

if (test) {
    aggregation = [...aggregation, ...passo4]; 
} else {
    // aggregation = [...aggregation, ...passo1]; 
    aggregation = [...aggregation, ...passo1]; 
   //  aggregation = [...aggregation, ...passo1b]; 
    aggregation = [...aggregation, ...passo1c]; 
    aggregation = [...aggregation, ...passo2]; 
    aggregation = [...aggregation, ...passo2b]; 
}

db.circuits.aggregate(aggregation);
