skip to Main Content

When i run this query:

db.friendRequests.aggregate([
        $lookup: {
          from: "users",
          localField: "author",
          foreignField: "_id",
          pipeline: [
            {
              $match: {
                $expr: {
                  friend_id: new mongoose.Types.ObjectId(userid),
                },
              },
            },
          ],
          as: "userdata",
        }
])

It returns every entry in the collection, but theres a pipeline in it. Then why is it not working?

Can you help me? Thanks!

Playground:
https://mongoplayground.net/p/Eh2j8lU4IQl

2

Answers


  1. For mongodb version under 5.0 (Thanks for the remark @user20042973):
    $lookup with localField and foreignField will ignore a pipeline. Remove them and add a let key in order to enable the pipeline.

    Login or Signup to reply.
  2. The friend_id field is present in the friendRequests collection (source for the aggregation) not the users collection which is the target for the $lookup. Therefore that predicate should come in a $match stage that precedes the $lookup:

    db.friendRequests.aggregate([
      {
        $match: {
          "friend_id": ObjectId("636a88de3e45346191cf4257")
        }
      },
      {
        $lookup: {
          from: "users",
          localField: "author",
          foreignField: "_id",
          as: "userdata"
        }
      }
    ])
    

    See how it works in this playground example. Note that I changed inventory to users assuming that was just a typo in the collection name in the provided playground link.


    Original answer

    This syntax is incorrect:

    $match: { 
      $expr: {
        friend_id: new mongoose.Types.ObjectId(userid),
      },
    }
    

    You should change it to either

    $match: { 
      friend_id: new mongoose.Types.ObjectId(userid),
    }
    

    Or

    $match: { 
      $expr: {
        $eq: [ 
          "$friend_id", new mongoose.Types.ObjectId(userid)
        ]
      },
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search