'Filter Out Result From Nested Array - MongoDB
I am trying to join & filter two collections.
Basically, I want to filter video content type from one collection & join the second collection data based upon element id.
collection_one
{
"elements": [{
"elementId": "ade28336-c34d-4357-a4c4-279820802a5db",
"type": "Unit",
"title": "TEST Unit",
"elements": [{
"elementId": "kajsdl28336-c34d-27492-a4c4-279820802a5db",
"type": "Unit",
"title": "TEST Unit",
"elements": [{
"elementId": "s87d9-c34d-27492-a4c4-279820802a5db",
"type": "Unit",
"title": "TEST Unit",
"elements": [{
"elementId": "a87sdf980-c34d-s897d-a4c4-279820802a5db",
"type": "video",
"title": "TEST Unit"
}]
},{
"elementId": "9cvb0fv-c34d-s897d-a4c4-279820802a5db",
"type": "video",
"title": "TEST Unit",
"elements": []
},{
"elementId": "a7sd9s-c34d-s897d-a4c4-279820802a5db",
"type": "video",
"title": "TEST Unit",
"elements": []
}]
}]
}]
}
Collection_two
{
"elementId": "a87sdf980-c34d-s897d-a4c4-279820802a5db",
"created_date": "2022-03-21T10:10:57.836Z",
"updated_date": "2022-03-21T10:10:57.836Z"
}
The expected result would be like this
{
"elementId": "a87sdf980-c34d-s897d-a4c4-279820802a5db",
"type": "video",
"title": "Test Unit",
"elementsMeta": {
"elementId": "a87sdf980-c34d-s897d-a4c4-279820802a5db",
"created_date": "2022-03-21T10:10:57.836Z",
"updated_date": "2022-03-21T10:10:57.836Z"
}
}
I tried with lookup its returning data with parents also & I don't want the parents in the result.
{
from: 'collection_two',
localField: 'collection_one.elementId',
foreignField: 'elementId',
let: {type:'video'},
pipeline: [],
as: 'content_metadata'
}
The result I am getting
{
"elementId": "ade28336-c34d-4357-a4c4-279820802a5db",
"type": "Unit",
"title": "TEST Unit",
"elements": [{
"elementId": "kajsdl28336-c34d-27492-a4c4-279820802a5db",
"type": "Unit",
"title": "TEST Unit",
"elements": [{
"elementId": "s87d9-c34d-27492-a4c4-279820802a5db",
"type": "Unit",
"title": "TEST Unit",
"elements": [{
"elementId": "a87sdf980-c34d-s897d-a4c4-279820802a5db",
"type": "video",
"title": "TEST Unit"
}]
}]
}]
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
