1

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();
1
  • Please take a look at the Aggregation Stages, the stages you are trying to use, and some examples. Commented Aug 6, 2020 at 7:21

1 Answer 1

4

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:{...}}
  ]
)
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks but I have lots of stuff going on. I updated the question with what I tried based on your answer but still no results and no errors.
@FKM: But is it even possible? Mongoose has no support for aggregating from queries. MongoDB documentation has db.collection.aggregate and db.aggregate and nothing else. Besides, everything you can do with a find() you can also do with $match, and you can sort and limit with aggregate as well.
@FKM the solution which I posted is application on mongo3.6 version and later. Which version are you currently working? And please keep in mind aggregate pipeline executes in sequence. Please consider keeping sort and limit after aggregate.
@Vibhav Singh Rohilla - I am using mongo db compass community version 1.21.2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.