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.

1 Answer 1

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

2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.