Skip to content

dot notation

Estimated time to read: 2 minutes

To access nested documents within an array field, MQL makes use of dot-notation.

Fields within a sub-document can be accessed

The field name from the sub-document, follows the top-level field separated by a dor and then wrapped in quotes. It's is essentially a path to the field to be queried within the array within the document.

For example to find all instances of "type" : "Point" within the start station location field, the following query could be used:

db.trips.findOne( {"station station location.type": "Point"} )

dot-notation can be used to traverse deep objects to get the last atomic non-document value in the hierachy.

Example

The query below looks at the first element in the relationships array using dot-notation. Array elements in most languages and data structures are enumerated staring from zero.

db.companies.find({ "relationships.0.person.last_name": "Zuckerberg" },
                  { "name": 1 }).pretty()

Example Breakdown

0: position of the first array element person: field name with a nested object as a value last_name: field name with the "person" sub-document "Zuckerberg": value to be searched for { "name": 1 }: projection to only include the company name in the resulting cursor

Further Examples

CEOs

Find the count of documents where, CEOs named Mark listed first in the relationships array.

db.companies.find({ "relationships.0.person.first_name": "Mark",
                    "relationships.0.title": { "$regex": "CEO" } },
                  { "name": 1 }).count()

Return the documents of the above example, in a pretty format!

db.companies.find({ "relationships.0.person.first_name": "Mark",
                    "relationships.0.title": {"$regex": "CEO" } },
                  { "name": 1 }).pretty()
Past CEOs

All senior executives named Mark listed in the relationships array who no longer work at their company.

To do this, the following queries shall be checked. { "is_past: true" } and { "person.first_name: "Mark" }. This can be done using an $elemMatch operator to look through every array element and match the conditions.

db.companies.find({ "relationships":
                      { "$elemMatch": { "is_past": true,
                                        "person.first_name": "Mark" } } },
                  { "name": 1 }).pretty()