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

Viewed 153

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"
        ]
}
2 Answers

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.

Related