Removing specific items from array with MongoDB

前端 未结 3 1200
后悔当初
后悔当初 2020-11-28 09:21

I am developing a web app using Codeigniter and MongoDB. The users can upload files and other users can comment on them.

I store the comments in an array called comm

相关标签:
3条回答
  • 2020-11-28 09:40

    If you can identify the comment item by matching userid, name or comment -- then you can remove that comment using update() command with $pull modifier along with the appropriate condition.

    If you cannot do as above, include an unique id in the comments (like UUID).

    To delete the comment, do the following:

    db.coll.update({<cond to identify document}, {$pull: {'comments': {'name': <name>}}} )
    

    If you use the id, which is preferred:

    db.coll.update({<cond to identify document}, {$pull: {'comments': {'id': <id>}}} )
    
    0 讨论(0)
  • 2020-11-28 09:41

    maybe you can remove comment by its 'created_at' time, as the time is unique.

    $db.coll.update({cond to identify document},{$pull:{'comments':{'created_at':<>}}})
    
    0 讨论(0)
  • 2020-11-28 10:00

    I think, you have add mongodb id to each comment when insert it. You can create a new mongodb id like this;

    $comment_id = new MongoID();
    

    Now, you can delete comments by id with $pull + $update like @smoorthy's answer.

    0 讨论(0)
提交回复
热议问题