Mongo Query Builder
The option.mongo() object provides a simple way to query MongoDB collections directly from Groovy scripts in 1Gateway.
It allows workflows and mappings to retrieve data from internal collections or integration-related datasets without needing to write raw MongoDB queries.
This is commonly used for:
- Looking up configuration or reference data
- Querying CMDB or inventory information
- Enriching messages with stored data
- Searching audit or transactional information
Creating a Mongo Query
Use option.mongo() with the target collection name:
db = option.mongo("collection_name")
Query Conditions
Equality (is)
Matches documents where the field equals a specific value.
db.is("status", "active")
db.is("type", "user")
Equivalent MongoDB query:
{
"status": "active",
"type": "user"
}
In (in)
Matches documents where the field value exists in a list.
db.in("status", ["active", "pending"])
db.in("category", ["A", "B"])
Equivalent MongoDB query:
{
"status": {
"$in": ["active", "pending"]
}
}
Regular Expression (regex)
Matches documents using regex patterns.
db.regex("name", "^John.*")
db.regex("email", ".*@gmail.com")
Example:
- Find users whose name starts with
John - Find all Gmail addresses
Less Than (lt)
Matches values lower than the specified value.
db.lt("age", 30)
db.lt("score", 100)
Equivalent MongoDB query:
{
"age": {
"$lt": 30
}
}
Greater Than (gt)
Matches values greater than the specified value.
db.gt("age", 18)
db.gt("score", 50)
Equivalent MongoDB query:
{
"age": {
"$gt": 18
}
}
Sorting
Sort Ascending
db.sort_asc("name")
db.sort_asc("createdAt")
Sort Descending
db.sort_desc("score")
db.sort_desc("updatedAt")
Pagination
Limit Results
Limits the number of returned documents.
db.limit(50)
Skip Results
Skips a number of documents.
db.skip(0)
Useful for pagination.
Execute the Query
Use .go() to execute the query and retrieve the results.
res = db.go()
The result contains the matching MongoDB documents.
Full Example
db = option.mongo("tickets")
db.is("status", "open")
db.in("priority", ["high", "critical"])
db.sort_desc("updatedAt")
db.limit(100)
db.skip(0)
res = db.go()
This example:
- Queries the
ticketscollection - Retrieves open tickets with high or critical priority
- Sorts by the latest updated tickets
- Returns the first 100 results
What is it used for
It allows Groovy scripts to:
- Retrieve additional context before mapping
- Make routing decisions based on stored data
- Enrich messages dynamically
- Query historical or CMDB information
Best Practices
- Use
limit()when querying large collections - Apply filters before sorting for better performance
- Use indexed fields whenever possible
- Avoid querying large collections without conditions
Summary
The option.mongo() object provides:
- Simple MongoDB querying from Groovy
- Conditional filtering
- Sorting and pagination
- Easy enrichment and lookup capabilities
It enables low-code access to persisted data directly inside 1Gateway.