MongoDB Query a specific field in an array

I have a MongoDB database structure that looks something like this.

{
    "peopleholder": {
        "people": [
            {
                "otherdata": "asdf",
                "name": "joe"
            },
            {
                "otherdata": "asdf",
                "name": "bob"
            }
        ]
    }
}

Now, I'm trying to construct a search query to select all people who have name "bob", right?

So, I've tried some things, looking at the $all suggestion, and come up with...

{
    "peopleholder": {
        "people": {
            "$all": [
                {
                    "name": "bob"
                }
            ]
        }
    }
}

I've also tried it with people just equal to {"name": "bob"}, as that appears to be shorthand.

1 answer

  • answered 2018-11-07 23:33 mostafazh

    This should do it:

    { "peopleholder.people.name": "bob"}
    

    Source Mongodb docs