Hi I am new to mongodb trying to achieve a output using mongodb aggregate I am trying to achieve a single array of objects instead of multiple array of objects can anyone help me to achieve my desired output
Below I have mentioned my model and I have mentioned my query, I am getting array of objects but I need a combined single array of objects I need to achieve it by mongodb query.
This is my mongodb model
db={
"teacher": [
{
"rating": 4,
"teacher_id": "123",
"course_count": 1,
},
{
"rating": 5,
"teacher_id": "456",
"course_count": 4,
},
{
"rating": 5,
"teacher_id": "no-exists",
"course_count": 4,
}
],
"course": [
{
"teacher_id": "123",
"cid": "1",
"advanced": true,
},
{
"teacher_id": "456",
"cid": "1",
"advanced": true,
}
]
}
this is my mongodb query
db.course.aggregate([
{
"$match": {
"cid": "1"
}
},
{
"$lookup": {
"localField": "teacher_id",
"from": "teacher",
"foreignField": "teacher_id",
"as": "teacher"
}
},
{
$unwind: {
path: "$teacher",
preserveNullAndEmptyArrays: true
}
},
{
$project: {
_id: 0,
cid: 1,
teacher: 1
}
},
])
I am getting this output
[
{
"cid": "1",
"teacher": {
"_id": ObjectId("5a934e000102030405000002"),
"course_count": 1,
"rating": 4,
"teacher_id": "123"
}
},
{
"cid": "1",
"teacher": {
"_id": ObjectId("5a934e000102030405000003"),
"course_count": 4,
"rating": 5,
"teacher_id": "456"
}
}
]
this is my desired output
{
"cid": "1",
"advance":true
"teacher": [{
"_id": ObjectId("5a934e000102030405000002"),
"course_count": 1,
"rating": 4,
"teacher_id": "123"
},
{
"_id": ObjectId("5a934e000102030405000003"),
"course_count": 4,
"rating": 5,
"teacher_id": "456"
}
]
}
teachers by thecidkey, and then inside that grouping, group again, this time by theteacherkey? That way, you'd end up with{"cid": "1","teacher" : [ ...]}.$push. Please take a look at the following, and let me know if it works for you: mongoplayground.net/p/oACyo7-JpbN