Skip to content
Advertisement

$elemMatch to fetch specific values inside array

I have a collection named ‘attendance’ that has an array:

JavaScript

I have been trying to query the values of the specific element in my array using $and and $elemMatch in:

JavaScript

But it still prints the other section rather than one. I want to output to be:

JavaScript

And I tried using the dot notation like:

JavaScript

Still no luck. I’m not sure if what I’m doing is right or not. Thanks in advance!

Advertisement

Answer

Option 1: find/elemMatch-> You will need to add the $elemMatch also to the project section of the find query as follow:

JavaScript

Explained:

Find query has the following syntax:db.collection.find({query},{project}) Adding the project section allow you to filter the expected output.

playground option 1

Option 2: Via aggregation/$filter:

JavaScript

Explaned:

Replace the original sections array with new ones where the array elements are filtered based on the provided criteria.

playground option 2

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement