I have a mongodb collection named students
, where there are 3 documents:
{
_id: ObjectId('66880dd88517a33fd8141e08'),
name: 'Mark',
courses: [
{course_id: ObjectId('6684e9c8122ef4d77a9dfd1a'), active: true},
{course_id: ObjectId('6684e9c8122ef4d77a9dfd1b'), active: false}
]
}
{
_id: ObjectId('668626f11b64d2e86632e7cb'),
name: 'John',
courses: [
{course_id: ObjectId('6684e9c8122ef4d77a9dfd1a'), active: false},
{course_id: ObjectId('6684e9c8122ef4d77a9dfd1b'), active: true}
]
}
{
_id: ObjectId('6684e3b628fcee8f24ead736'),
name: 'Doe',
courses: [
{course_id: ObjectId('6684e9c8122ef4d77a9dfd1a'), active: true},
{course_id: ObjectId('6684e9c8122ef4d77a9dfd1b'), active: true}
]
}
I have another collection named courses
, where there are 2 documents:
{
_id: ObjectId('6684e9c8122ef4d77a9dfd1a'),
note: 'Course on mongodb.'
}
{
_id: ObjectId('6684e9c8122ef4d77a9dfd1b'),
note: 'Advanced mongodb course.'
}
I want to query on courses collection and get desired document matched by given _id
. This document should contain an array named students
. In this array each student should contain a courses
array where only those courses should reside which have matching course_id
with given _id
and active: true
.
Suppose, given _id
is 6684e9c8122ef4d77a9dfd1b
. So, my desired output should look like this:
{
_id: ObjectId('6684e9c8122ef4d77a9dfd1b'),
note: 'Advanced mongodb course.',
students: [
{
_id: ObjectId('668626f11b64d2e86632e7cb'),
name: 'John',
courses: [
{course_id: ObjectId('6684e9c8122ef4d77a9dfd1b'), active: true}
]
},
{
_id: ObjectId('6684e3b628fcee8f24ead736'),
name: 'Doe',
courses: [
{course_id: ObjectId('6684e9c8122ef4d77a9dfd1b'), active: true}
]
}
]
}
I am using express, mongodb and mongoose. I tried this query:
app.get('/:id', async function (req, res) {
try {
const batch = await Course.aggregate([
{"$match": {"_id": req.params.id}},
{"$lookup": {
"from": "students",
"localField": "_id",
"foreignField": "courses.course_id",
"as": "students"
}
}
])
res.send(batch)
} catch (error) {
res.json({
error: error
})
}
})
This query doesn’t provide me my desired output. How to get my desired output?
Tahsin Al Mahi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.