In mongoose I am trying to fetch the inner record which match with specific condition. but it always return me both records, like it only treat the parent node rather than child.
$project aggregate function doesn't seems working as I expected `
[{
"_id": {
"$oid": "636b9958d6ea5d0cc85d20a6"
},
"project_type": 1,
"title": "Pariatur Aut repreh",
"id": 4,
"drawings": [
{
"id": 1,
"assigned_to": 4,
"assigned_name": "Desirae Sandoval",
"assigned_by": 3
},
{
"id": 1,
"assigned_to": 6,
"assigned_name": "Desirae Sandoval",
"assigned_by": 3
}
],
"status": 1,
"created_at": {
"$date": {
"$numberLong": "1667995992724"
}
}
}]
`
I am expecting to get only that drawing which is assigned_to : 6
I have tried aggregate, match, project everything but none of them working, it always fetch both of the drawing, but I am expecting to fetch only one drawing
This what I am expecting
[{
"_id": {
"$oid": "636b9958d6ea5d0cc85d20a6"
},
"project_type": 1,
"title": "Pariatur Aut repreh",
"id": 4,
"drawings": [
{
"id": 1,
"assigned_to": 6,
"assigned_name": "Desirae Sandoval",
"assigned_by": 3
}
],
"status": 1,
"created_at": {
"$date": {
"$numberLong": "1667995992724"
}
}
}]
CodePudding user response:
Use a filter
db.collection.aggregate([
{
$match: {
"drawings.assigned_to": 6
}
},
{
$project: {
project_type: 1,
title: 1,
id: 1,
status: 1,
created_at: 1,
drawings: {
$filter: {
input: "$drawings",
as: "drawings",
cond: {
$eq: [
"$$drawings.assigned_to",
6
]
}
}
}
}
},
])
Edit: Add a match to remove all documents without any documents with any drawings.assigned_to
of 6