Home > OS >  MongoDB $match in a aggregate lookup not working as expected
MongoDB $match in a aggregate lookup not working as expected

Time:11-22

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?

Heres the friendRequests and the users collection:

friendrequests

users

Can you help me? Thanks!

CodePudding user response:

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)
    ]
  },
}

CodePudding user response:

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.

  • Related