Example of a MongoDB Query that uses $elemMatch
Snowpal API: When do you need to use $elemMatch in a MongoDB query?
Check out our Classroom API Postman Collection and subscribe to it on AWS Marketplace.
A simple example to illustrate MongoDB’s $elemMatch
. In the code below, we fetch courses a teacher has access to.
There are 3 arguments to this method:
user
: A user object so we can return courses this particular user has access to.acl
: What level of access should this teacher have?archived
: Return archived or unarchived courses as dictated by this boolean.
Could the query have looked like this instead?
Let’s try removing the use of $elemMatch
and make the query simpler.
where :_type.in => [PlanitApp::PrivateTeacherCourse, PlanitApp::SharedTeacherCourse],
:archived => archived,
:"authorization.users.id" => user.id,
:"authorization.users.acl" => acl
Will this work and return what we expect? Not quite.
Our intent is to return only those courses where the given user (user.id) has a certain level of access (acl) but authorization.users
is a nested array of users with multiple attributes (with ID and ACL being two of those). Though we want both those conditions to be applied within that nested array in the document, not using $elemMatch
will not scope the results to only those courses as it will instead apply each of those conditions separately across different documents in that collection thereby returning incorrect results.
So, when you use nested arrays in a NoSQL document, be wary of this.
Snowpal Products
Backends as Services on AWS Marketplace
Mobile Apps on App Store and Play Store
Web App
Education Platform for Learners and Course Creators