Match by 2 fields in one subobject

Hi, I would like to match all “schools” that contain some student “Peter” with “excelent” level.
I tried:

{
"students.name": "Peter",
"students.level": "excelent"
}

but it returns also documents where “Peter” and “excelent” are not related to the same person.

My data:

{
    "schoolName": "London school"
    "students": [{
        "name": "Peter",
        "level": "middle"
    }, {
        "name": "Jane",
        "level": "excelent"
	}]
}

Is it possible somehow? I’m new in MongoDB…

Hi @Daniel_Reznicek,

Sure. You need to use $elemMatch in your queries:

 db.schools.find(
    {"students": {"$elemMatch": {"name": "peter", "level": "excellent"}}});

Of course you can index those fields or the main array field to better search this syntax.

Best
Pavel

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.