Using MongoDB $pull to delete documents within an Array

前端 未结 3 1416
Happy的楠姐
Happy的楠姐 2020-12-05 10:52

I have a collection in MongoDB, which is like following:

{
    \"_id\" : \"5327010328645530500\",
    \"members\" : [
        {
            \"participationCo         


        
相关标签:
3条回答
  • 2020-12-05 11:15

    In the meantime the update method is deprecated. Therefore one possible up-to-date solution to this would be using the updateMany method instead.

    db.clusters.updateMany({}, 
        {$pull: {members: {tweetID: '5327010328645530500'}}})
    
    0 讨论(0)
  • 2020-12-05 11:29

    That's exactly what the $pull operator does, so in the shell you could use an update like:

    db.clusters.update({}, 
        {$pull: {members: {tweetID: '5327010328645530500'}}}, 
        {multi: true})
    

    Set the multi option so that every document is updated, not just the first one.

    0 讨论(0)
  • 2020-12-05 11:32

    This will delete multiple tweets in a single query just pass an array to $in:-

    db.clusters.update({}, 
    {$pull: {members: {$in: [ {tweetID: '5327010328645530500'},{"tweetID" : "2820402625046999289"} ] } } }, 
    {multi: true});
    

    The above method doesnt work in mongoose so for mongoose do:-

     db.clusters.update({}, 
    {$pull: {members:[ {tweetID: '5327010328645530500'},{"tweetID" : "2820402625046999289"} ]  } });
    
    0 讨论(0)
提交回复
热议问题