0
  • The given below is my document, I need to remove comments array of an object from the document, so I can pass the document id from the frontend, with postId.
  • I am struct please help me.
{
  likes: [],
  _id: 5ea4375f49e4355094073330,
  title: 'abc',
  body: 'abc',
  photo: 'no pic',
  postedBy: 5e9aa457de91831e5c9f5005,
  comments: [
    {
      _id: 5ea437c2a584ce5ac0147da1,
      text: 'sadsadsad',
      postedBy: [Object]
    },
    {
      _id: 5ea437c5a584ce5ac0147da2,
      text: 'sadsadsad',
      postedBy: [Object]
    },
    {
      _id: 5ea437c7a584ce5ac0147da3,
      text: 'sadsadsad',
      postedBy: [Object]
    }
  ],
  __v: 0
}
2
  • 1
    Do you want to remove the specific comment or whole array? Commented Apr 25, 2020 at 13:39
  • i need to remove specific comment object { _id: 5ea437c2a584ce5ac0147da1, text: 'sadsadsad', postedBy: [Object] } this alone in mongo db. Commented Apr 25, 2020 at 13:45

1 Answer 1

1

If you want to remove a specific element from the array of comments you can use the following query:

db.mycollection. updateOne(
       {'_id': ObjectId("5ea4375f49e4355094073330")},
       { $pull: { "comments" : { _id: ObjectId("5ea437c2a584ce5ac0147da1") } } }
);

If you want to remove comment object from every element in your collection you can simply remove the first argument from update. Something like this:

db.mycollection.updateMany(
       { },
       { $pull: { "comments" : { _id: ObjectId("5ea437c2a584ce5ac0147da1") } } }
);
Sign up to request clarification or add additional context in comments.

5 Comments

(node:15168) DeprecationWarning: collection.update is deprecated. Use updateOne, updateMany, or bulkWrite instead. i have already try these things dude, mongo db through error.
I just update my answer. What kind of errors? The following is warning is not an error. You can read more for deprecation on: mongoosejs.com/docs/deprecations.html These queries work fine.
Arunkumar any luck?
Post.findByIdAndUpdate( req.params.postId, { $pull: { "comments" : { _id: req.params.commentId } }, }, { new: true, } ).exec((error, result) => { if (error) { return res.status(402).json(error); } else { res.json(result); } }); this will work
findByIdAndUpdate is doing the same as my given answer, because it's based on updateOne(). The thing is that you never mention in your question that you want to create a node.js function. You ask for MongoDB query. So basically my answer is correct. Please consider in the future to ask exactly what you need.

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.