0

Let's say I have this collection in MongoDB:

{
    "_id" : ObjectId("5890e5ea619737392c257846"),
    "email" : "ewrt@ert.com",
    "pass" : "123456",
    "firstName" : "sdlriugth",
    "lastName" : "sdfligkjh",
    "movies" : [ 
        ObjectId("5890e5ec619737392c257847"), 
        ObjectId("5890e5ed619737392c257848"), 
        ObjectId("5890e5ee619737392c257849"), 
        ObjectId("5890e5ee619737392c25784a")
    ]
}
{
    "_id" : ObjectId("5890e5f8619737392c25784c"),
    "email" : "wieruy@dgf.com",
    "pass" : "123456",
    "firstName" : "yjhtgj",
    "lastName" : "vbnvbng",
    "movies" : [ 
        ObjectId("5890e5fa619737392c25784d"), 
        ObjectId("5890e5fb619737392c25784e"), 
        ObjectId("5890e5fc619737392c25784f")
    ]
}

There are 2 users, each user has an array of movies id's.

I want to do a query that will remove a specific movie Id from the user that has this movie.

let's say if I'll remove the movie id : "5890e5ee619737392c25784a" I will get:

    {
    "_id" : ObjectId("5890e5ea619737392c257846"),
    "email" : "ewrt@ert.com",
    "pass" : "123456",
    "firstName" : "sdlriugth",
    "lastName" : "sdfligkjh",
    "movies" : [ 
        ObjectId("5890e5ec619737392c257847"), 
        ObjectId("5890e5ed619737392c257848"), 
        ObjectId("5890e5ee619737392c257849"), 
    ]
}
{
    "_id" : ObjectId("5890e5f8619737392c25784c"),
    "email" : "wieruy@dgf.com",
    "pass" : "123456",
    "firstName" : "yjhtgj",
    "lastName" : "vbnvbng",
    "movies" : [ 
        ObjectId("5890e5fa619737392c25784d"), 
        ObjectId("5890e5fb619737392c25784e"), 
        ObjectId("5890e5fc619737392c25784f")
    ]
}

P.S I what the changes to be made on all relevant documents. (many users can have the same movie id)

Thanks :)

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
shayp
  • 44
  • 4
  • I forgot to tell that I want the changes to be made on all relevant documents and not on specific user. – shayp Feb 01 '17 at 17:20

1 Answers1

0

You can use the $pull operator. So in your case the query would be

db.collection.updateOne({"_id": ObjectId("5890e5ea619737392c257846")},
{"$pull": {"movies": ObjectId("5890e5ee619737392c25784a")}})
masterforker
  • 2,443
  • 2
  • 25
  • 39