0

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" } )
1
  • @DanDascalescu Not the same question. He just wants to remove one array element. It's the .remove() method that is wrong here. Commented Feb 27, 2014 at 10:22

2 Answers 2

1

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/

Sign up to request clarification or add additional context in comments.

1 Comment

@Gireesh my bad, I didn't add the second part of what I did
0

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.