1

I saw a lot of similar questions about this but couldn't make it work in my collection.

How can I delete a specific comment (you can assume that I know the userId).

For example, I want to remove comment with commentId=3 and I know that it's under userId=1.

[
{
    userId: "1",
    posts: [
        {
            postId: "2",
            comments: [
                {
                    commentId: "3",
                    ...
                },
                ...
            ]
        },
        ...
    ]
},
...
]

Thanks!

2 Answers 2

1

This works with Mongodb 4.2 and will remove first array entry from "comments" if it matches the "commentId" 3

db.posts.update(
    {"userId" : "1"}, 
    {$pull : {"posts.$[].comments" : {"commentId":"3"}}}
)

If you would like to remove all array entries use:

db.posts.update(
    {"userId" : "1"}, 
    {$pull : {"posts.$[].comments" : {"commentId":"3"}}},
    {"multi": true}
)
Sign up to request clarification or add additional context in comments.

1 Comment

Only one comment - update is deprecated, use updateOne/updateMany instead
0

Have you tried using the deleteOne()function ? try and have a look on MongoDb documentation. MongoDbDocumentation

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.