0

My users collection contains:

{
    _id: "1",
    posts: [
        {
            _id: "12",
            comments: [
                {
                    _id: "123",
                    userId: "5",
                    ...
                },
                ...
            ]
        },
        ...
    ]
},
...

I want to get all the comments the belongs to specific user id (userId prop).

How can I achieve that?

Thanks

user3343396
  • 725
  • 2
  • 13
  • 25

1 Answers1

0

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

Mohammed Yousry
  • 2,134
  • 1
  • 5
  • 7