Reputation: 4254
//issues-collection
[
{
project: ObjectId("67"), // ref to a project
id: 101,
assignedTo: ObjectId("1212") // ref to a user
}
]
//project-collection
[
{
_id: ObjectId("67"),
title: "Proj 1",
members: [
{
_id: ObjectId("213213"),
user: ObjectId("1212"), // ref to a user
discipline: "Architect"
}
]
}
]
I need a query for the issue collection on the disciplin field from the project collection
The $lookup
should be used. Something like this.
const getIssuesByDiscipline = (projectId, discpline: string) => {
const res = mongoose.model("issues").aggregate([
{
$lookup: {
from: "project",
localField: "assignedTo",
foreignField: "members.user",
as: "project",
//pipeline: ?
}
]
},
}...
Not sure how to use $lookup when the foregin field is an array. Maybe something with pipeline
?
Any suggestion?
Upvotes: 1
Views: 50
Reputation: 16033
I think you want something like:
MongoDB version 5.0 or higher:
project
from issues
collection to find the documents on project
collection with the matching _id
$filter
relevant user
sdb.issues.aggregate([
{$lookup: {
from: "project",
localField: "project",
foreignField: "_id",
as: "project",
let: {assignedTo: "$assignedTo"},
pipeline: [
{$project: {
members: {$filter: {
input: "$members",
cond: {$eq: ["$$this.user", "$$assignedTo"]}
}}
}}
]
}}
])
See how it works on the playground example
MongoDB versions before 5.0:
Can't use both localField, foreignField
with a pipeline. Instead, add another phase to the pipeline (as a first phase) to match the relevant documents:
db.issues.aggregate([
{$lookup: {
from: "project",
as: "project",
let: {assignedTo: "$assignedTo", project: "$project"},
pipeline: [
{$match: {$expr: {$eq: ["$$project", "$_id"]}}},
{$project: {
members: {$filter: {
input: "$members",
cond: {$eq: ["$$this.user", "$$assignedTo"]}
}}
}}
]
}}
])
See how it works on the playground example
Upvotes: 1