-1

this is my mongodb object

{
    "_id" : ObjectId("4faaba123412d654fe83hg876"),
    "user_id" : 123456,
    "posters" : [ 123456,1111,456789,3333]
}

i want to add an item to posters array , or remove one how could i do it ?

its nested updating.

i saw some question around stackoverflow , but i didnt found any answer how to remove object from the array , lets say 3333 there .

so the result will be :

{
    "_id" : ObjectId("4faaba123412d654fe83hg876"),
    "user_id" : 123456,
    "posters" : [ 123456,1111,456789]
}

1

2 Answers 2

0

Use $pull.

db.collection.update(
    { posters: "3333" },
    { $pull: { posters: "3333" } },
    { multi: true }
)
Sign up to request clarification or add additional context in comments.

1 Comment

Please do not answer direct dups, let those be closed, that makes users do their homework first rather than posting everything they want :-)
0

Use $push to add something into an array :

db.collection.update(
{ $push:
    {
        "posters" : "0000"
    }
}
)

Use $pull to remove something from an array:

db.collection.update(
{ $pull:
    {
        "posters" : "3333"
    }
}, True
)


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.