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

Oshrr Hagag
  • 21
  • 1
  • 3
  • Does this answer your question? [Using MongoDB $pull to delete documents within an Array](https://stackoverflow.com/questions/15121758/using-mongodb-pull-to-delete-documents-within-an-array) – whoami - fakeFaceTrueSoul Jan 23 '20 at 21:03

2 Answers2

0

Use $pull.

db.collection.update(
    { posters: "3333" },
    { $pull: { posters: "3333" } },
    { multi: true }
)
Tom Slabbaert
  • 21,288
  • 10
  • 30
  • 43
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
)


Ananthu M
  • 77
  • 5