Using MongoDB $pull to delete documents within an Array

北慕城南 提交于 2019-12-28 12:32:35

问题


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

{
    "_id" : "5327010328645530500",
    "members" : [
        {
            "participationCoeff" : 1,
            "tweetID" : "5327010328645530500"
        },
        {
            "participationCoeff" : 1,
            "tweetID" : "2820402625046999289"
        },
        {
            "participationCoeff" : 0.6666666666666666,
            "tweetID" : "6122060484520699114"
        },
        {
            "participationCoeff" : 1,
            "tweetID" : "4656669980325872747"
        }
    ]
}
{
    "_id" : "2646953848367646922",
    "members" : [
        {
            "participationCoeff" : 1,
            "tweetID" : "2646953848367646922"
        },
        {
            "participationCoeff" : 0.75,
            "tweetID" : "7750833069621794130"
        },
        {
            "participationCoeff" : 0.5,
            "tweetID" : "6271782334664128453"
        }
    ]
}

Basically, collection have clusters, where a cluster has an _id field and a members field. Members field is an array of documents, having following format.

{
            "participationCoeff" : 1,
            "tweetID" : "5327010328645530500"
        }

Now, from time to time, I have to delete these sub-documents in members attribute of cluster document, by matching tweetID.

However, I'm not able to find a query to achieve this effect. Basically, a tweetID will participate in many clusters, and hence will appear in multiple sub-documents of 'members' attribute of various clusters. I want to supply a bulk $pull operation, where I can remove all the sub-documents in all the clusters (i.e. their members attribute) which match on a particular tweetID.

Some help and intuition will be really helpful.


回答1:


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.




回答2:


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"} ]  } });


来源:https://stackoverflow.com/questions/15121758/using-mongodb-pull-to-delete-documents-within-an-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!