you can try this
db.collection.aggregate([
{
$match: {
"posts.comments.user": "userId1" // note that you need to use objectId here if the user property in the comments array is an objectId
}
},
{
$unwind: "$posts"
},
{
$project: {
"posts.comments": {
$filter: {
input: "$posts.comments",
as: "comment",
cond: {
$eq: [
"$$comment.user",
"userId1"
]
}
}
}
}
},
{
$group: {
_id: "$_id",
posts: {
$push: "$posts"
}
}
}
])
test it here Mongo Playground
> Update
the above query will get an array of documents, each document has posts array, and each post element has comments array
if you need just the comments array belong to some user, then we can use something like this
db.collection.aggregate([
{
$match: {
"posts.comments.user": "userId1"
}
},
{
$unwind: "$posts"
},
{
$project: {
"posts.comments": {
$filter: {
input: "$posts.comments",
as: "comment",
cond: {
$eq: [
"$$comment.user",
"userId1"
]
}
}
}
}
},
{
$unwind: "$posts.comments"
},
{
$group: {
_id: null,
comments: {
$push: "$posts.comments"
}
}
},
{
$project: {
_id: 0
}
}
])
and test it here Mongo Playground 2