$lookup : return model if reference field is not empty

Viewed 264

I have College model which has ref :"University". each college has 1 university when the college is created.

so I'm trying to get all the colleges where the uuid of the university matches the request query.

So i tried the following :

  const myAggregate = College.aggregate([
    {
      $match: {
        language: req.query.language,
        display_language: req.query.display_language
      }
    },
    {
      $lookup: {
        from: 'unis', // UNIVERSITY COLLECTION
        pipeline: [
          {
            $match: {
              $expr: {
                $eq: ["$uuid", req.query.id]
              }
            }
          }
        ],
        as: 'univ',
      },
    },
    {
      $sort: { createdAt: -1 },
    },
  ])

so the above code when the query is provided and it does not equal the university UUID , it fetches all the colleges but the univ array is empty of each college.

is it possible to only show the colleges when the uuid equals the query id and not show an empty array of univ ?

1 Answers

You could do unwind to remove empty ones.

Doc reference:https://docs.mongodb.com/manual/reference/operator/aggregation/unwind/

 const myAggregate = College.aggregate([
    {
      $match: {
        language: req.query.language,
        display_language: req.query.display_language
      }
    },
    {
      $lookup: {
        from: 'unis', // UNIVERSITY COLLECTION
        pipeline: [
          {
            $match: {
              $expr: {
                $eq: ["$uuid", req.query.id]
              }
            }
          }
        ],
        as: 'univ',
      },
    },
   {"$unwind":{
 path: '$univ',
preserveNullAndEmptyArrays: false}},
    {
      $sort: { createdAt: -1 },
    },
  ])
Related