GGGGG
GGGGG

Reputation: 159

MongoDB: how to delete an object from a document in a nested array

My doc is like this

"page_elements" : [
        {
                "type" : "gallery",
                "words" : [
                        "gallery",
                        "photos"
                ]
        },
        {
                "type" : "cart",
                "words" : [
                        "cart",
                        "shop"
                ]
        },
        {
                "type" : "Privacy",
                "words" : [
                        "privacy",
                        "policy",
                        "privacy policy"
                ]
        },
        {
                "type" : "cart",
                "words" : [
                        "cart",
                        "shopping cart",
                        "buy now",
                        "add to cart",
                        "add to basket"
                ]
        }

by mistake, I've updated cart two times. now, i need to remove the first cart in the array and keep the rest of the document.

Here, I need to delete

{
    "type" : "cart",
    "words" : [
        "cart",
        "shop"
    ]
}

I tried this..

db.ds_master_language_words.remove( { "page_elements.type" : "cart" } )

Upvotes: 0

Views: 580

Answers (2)

Neil Lunn
Neil Lunn

Reputation: 151072

You don't want to remove, you want to update. $unset will get rid of the field and you know the position:

db.ds_master_language_words.update(
    { <your_document_id_match > },
    { $unset: { "page_elements.1": ""}}
)

That will set to null in the array, but now that is easy to remove with $pull:

db.ds_master_language_words.update(
    { <your_document_id_match > },
    { $pull: { "page_elements": null }}
)

Also see the documentation for the update method

http://docs.mongodb.org/manual/reference/method/db.collection.update/

Upvotes: 1

JohnnyHK
JohnnyHK

Reputation: 311835

You can do this with $pull by giving it a page_elements value that matches the array element to remove:

db.ds_master_language_words.update({}, {
    $pull: {page_elements: {
       "type": "cart",
       "words": ["cart", "shop"]
    }}})

Upvotes: 0

Related Questions