usal2100
usal2100

Reputation: 33

MongoDB - how do I pull the record based on the first element in array

Here are 2 documents in the attached file. I need to pull the title field based on the filter (Harrison Ford is the 1st element in the actor field). So I need to pull the 2nd document. Thanks for your help.

{
        "_id" : ObjectId("5e66e96a2f86fd04deaa59c5"),
        "title" : "Star Trek Into Darkness",
        "actors" : [
                "Chris Pine",
                "Zachary Quinto",
                "Harrison Ford",
                "Karl Urban"
        ]
}
{
        "_id" : ObjectId("5e66e96a2f86fd04deaa59c6"),
        "title" : "Raiders of the lost ark",
        "actors" : [
                "Harrison Ford",
                "Jonathan Frakes",
                "Brent Spiner",
                "LeVar Burton"
        ]
}

Upvotes: 2

Views: 302

Answers (2)

Kuldeep Mishra
Kuldeep Mishra

Reputation: 4040

db.collection.update({_id:'Your match id'}, {$pull:{actors:'Jonathan Frakes'}});

you can pull record with $pull and then update that record. Please check below link

https://docs.mongodb.com/manual/reference/operator/update/pull/

Upvotes: 0

Dĵ ΝιΓΞΗΛψΚ
Dĵ ΝιΓΞΗΛψΚ

Reputation: 5669

so you want to get the title of a movie that has Harrison Ford as the first actor right? if so, give this a try:

db.collection.find(
    { 'actors.0': 'Harrison Ford' },
    { title: 1, _id: 0 }
)

https://mongoplayground.net/p/f4-o13NjYNc

btw, when you say pull it may confuse people because there's a $pull operator in mongodb.

Upvotes: 1

Related Questions