- Stitch >
- Introduction >
- Live Examples
Query Anywhere with Stitch¶
You can query data stored in MongoDB directly from your client application code with the MongoDB query language. Data access rules defined on the Stitch server for each MongoDB collection let you securely filter results based on the logged in user or the content of each document.
Query MongoDB¶
The employees
collection contains documents describing each
employee in an example company. Each document includes the employee’s
name, email, role, salary, and information on the employee’s manager.
In the following example, we query the employees
collection for all
documents and display the formatted results in a table.
Live Example
Try uncommenting the limit
and sort
read options in the
query. The results displayed in the table should update to reflect
your changes.
Protect Data with Rules¶
You may not want to allow every employee to see the data of every other employee. We can use collection rules to control the data that each user can access without changing the query pattern.
For the following example, we’ve copied all of the employees
collection data into a new collection named direct_reports
.
This collection is protected by a MongoDB Service rule that only allows
a query to return documents that describe the logged in user or one of
their direct reports.
These conditions are configured as two separate roles, isThisPerson
and isManager
, that are evaluated relative to the logged in user on
each query. The assigned role is determined by the following
apply_when
expressions:
If the logged in user’s email address matches the value in the email
field of a document, that document describes the user so we allow them
to read it. We also allow users to read documents that describe their
direct reports, i.e. when the user’s email matches the manager.email
field. If neither of these conditions are met for a specific document,
Stitch transparently withholds that document from the user.

Live Example
Try changing the logged in user in the initializeClient
function to jane.schmoe@company.com
. You should see a different
set of direct reports listed in the table.