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
For mongodb version under 5.0 (Thanks for the remark @user20042973):
$lookup
withlocalField
andforeignField
will ignore apipeline
. Remove them and add alet
key in order to enable the pipeline.The
friend_id
field is present in thefriendRequests
collection (source for the aggregation) not theusers
collection which is the target for the$lookup
. Therefore that predicate should come in a$match
stage that precedes the$lookup
:See how it works in this playground example. Note that I changed
inventory
tousers
assuming that was just a typo in the collection name in the provided playground link.Original answer
This syntax is incorrect:
You should change it to either
Or