0

So I have a Collection named Pages, and inside of this collection, each page has an array of Widgets, each widget has an uuid which I use to identify each widget.

Pages [ 
     widgets : [{uuid : "someuuid"}, {uuid : "otheruuid"}]
]

I need to remove an item from a widgets array and update the collection. So I read in this post about how to remove items in an array (Mongo DB approach). Example of the post:

db.people.update({"name":"dannie"}, {'$pull': {"interests": "guitar"}})

I tried it, but it didn't work for my project, Dont know why, I am not sure why, I don't know how to write the mongodb instructions

So since I have to keep working I did something like this:

//random function to get index of an object in the array;
var indexOf = myfunction.getIndexOfObject()
if (indexOf > -1) {
    //remove the item in the array of the Active Page
    activePage.widgets.splice(indexOf, 1);
    //update the collection
    Pages.update({_id : activePage._id},activePage); 
}

I would like to know if my approach is correct; it works fine without any problems. But I dont know if could have any issue or caveat in performance or security or whatever other thing, since the documentation approach is totally different:

Documentation approach:

http://docs.mongodb.org/manual/reference/operator/update/pull/

db.cpuinfo.update(
                   { flags: "msr" },
                   { $pull: { flags: "msr" } },
                   { multi: true }
                 )

thanks for the support.

Community
  • 1
  • 1
ncubica
  • 8,169
  • 9
  • 54
  • 72

1 Answers1

1

Although whatever you are doing seems to be correct but I tired using $pull for updating array I could do it. I created a sample page collections and inserted following docs

db.pages.insert({widgets : [{uuid : "someuuid1"}, {uuid : "otheruuid2"}]});
db.pages.insert({widgets : [{uuid : "someuuid2"}, {uuid : "otheruuid3"}]});
db.pages.insert({widgets : [{uuid : "someuuid3"}, {uuid : "otheruuid3"}]});
db.pages.insert({widgets : [{uuid : "someuuid3"}, {uuid : "otheruuid4"}]});

The I ran update query to pull elements

db.pages.update({},{$pull : {"widgets" : {uuid : "otheruuid3"}}}, {multi:true});

I can see document 2 and 3 do not have "uuid : otheruuid3" in widgets. Not really sure what issue you are facing

Vijay Rawat
  • 241
  • 2
  • 7
  • Ohh actually I never used the multi:true thats new for me.. what do that property? – ncubica Sep 23 '14 at 07:19
  • 1
    {multi:true} is the expression for updating all documents matching the criterion by default it is false and in that case only one document is updated. See the link below http://docs.mongodb.org/manual/reference/method/db.collection.update/#multi-parameter/#multi-parameter – Vijay Rawat Sep 23 '14 at 12:54