March 27th, 2016

MongoDB Query: $elemMatch vs. Dot Notation

In MongoDB query, Dot notation is to match by specific fields in an embedded document. When the field holds an array of embedded documents, then to match the field, concatenate the name of the field that contains the array, with a dot (.) and the name of the field in the embedded document.

{ <array field name>.<embedded document field> : <value> }

To specify multiple criteria on an array of embedded documents such that AT LEAST ONE embedded document satisfies all the specified criteria, $elemMatch operator is used.

{ <array field name>: { $elemMatch: { <query1>, <query2>, ... } } }

Let us take an example to understand it. Consider schoolinfo collection includes following documents

February 21st, 2016

MongoDB Query: Select and Filter Child Array

If you are using embedded document to model one to many relationships in MongoDB, sometimes you might need to get child data only depends on the report. This post explains some experiments related to select and filter child array with MongoDB queries. Consider a collection school with the following documents: