FKM
FKM

Reputation: 143

MongoDB aggregate lookup not working with multiple parameters

I am pulling data from comments table and it works. I want to do a join equivalent with performance in mind on the users collection to get details about the user who commented.

Here is my code where I use Next js. I added the aggregate/ lookup and now I dont get anything back.

  const from = req.query.from ? new Date(req.query.from) : new Date();
  const postId = req.query.by;
  const comments = await req.db
    .collection('commentsPosts')
    .find({
      commentedAt: {
        $lte: from,
      },
      ...(postId && { postId }),
    })
    .sort({ commentedAt: -1 })
    .limit(parseInt(req.query.limit, 10) || 10)

    //This part is not working and breaking the whole query
    .aggregate({
      $lookup:{
          from:"users",
          localField:"createdBy",
          foreignField:"_id",
          as:"commenterDetails"
          }
      })
     /////////////
    .toArray();

  res.send({ comments });

Edit

Updated as per the answer below but still no results

   .collection('commentsPosts')
    .aggregate(
      [
       {$match:{
        commentedAt: {
          $lte: from,
        },
        ...(postId && { postId }),
        }
        .sort({ commentedAt: -1 })
        .limit(parseInt(req.query.limit, 10) || 10)
       },
       {$lookup:
          {
                from:"users",
                localField:"createdBy",
                foreignField:"_id",
                as:"commenterDetails"
          }
        }
      ]
    ).toArray();

Upvotes: 1

Views: 555

Answers (1)

Vibhav Singh Rohilla
Vibhav Singh Rohilla

Reputation: 768

you do not need to do a find() when you are planning to use aggregate()

Remove the find() and introduce a $match in aggregate pipeline.

db.comments.aggregate(
  [
   {$match:{commentedAt:{$gt:QUERY_CLAUSE_HERE}},
   {$lookup:{...}}
  ]
)

Upvotes: 4

Related Questions