Overview
Collection serves as a managed database service integrated directly into the Prisme.ai platform:Data Storage
Query Capabilities
Data Management
Integration Ready
Release Note: Collection with PostgreSQL
With this new release, Collection instructions become compatible with postgresql database and the same MongoDB queries / updates syntax as usual.This also brings performance improvements and new features, but with a few breaking changes and mongodb/postgres subtle differences to note.
Schema Configuration
Cross-Database Compatibility
Breaking Changes
New Features
Breaking Changes
Connection Pooling
- Since mongodb requests were previously executed by prismeai-functions microservice, the total number of mongodb clients opened were directly tied to the prismeai-functions replicas number & scaling
- Now that collections clients are only opened from
prismeai-runtime(which supports multithreading),minPoolSizeandmaxPoolSizemust be scaled relative toRUNNER_MAX_THREADS. - Example: if
RUNNER_MAX_THREADS=2, then divide your pool sizes by 2.
Required permissions
- The new collection schemas enforcement now requires 3 more mongodb user permissions (& their equivalent SQL) :
- listCollections, listIndexes, dropIndexes
Update Instructions
Collection.updateManyno longer supportsoptions.upsertCollection.updateOnedeprecatesoptions.upsert: Use the dedicatedCollection.upsertinstruction instead.Collection.updateOneandCollection.updateManyno longer supportsoptions.replace.
Allowed Update Operators
Safer Deletes and Updates
updateOne,updateMany,deleteOneanddeleteManynow raise an error if the query is empty/undefined.- To allow matching all documents, use the
overrideSecurity: trueparameter.
Schema Enforcement
- All collections must now define collectionName and properties inside their app config, see an example config below.
- Queries referencing unknown fields will raise errors.
- Insert/update operations with unknown fields will also fail.
- All properties defined in the schema will now be initialized to null and returned as-is by
findif they were not initialized (and nullable)
🆕 New Features
- Aggregate
- Distinct
Key Features
- Document Storage
- Query Capabilities
- Data Manipulation
- Advanced Features
- Schema enforcement: Ensure your data respect a predefined schema
- Nested Data Support: Store complex, hierarchical data
- Data Types: Support for strings, numbers, booleans, arrays, objects, dates
- Automatic Indexing: Optimized for fast retrieval
How Collection Works
Collection provides a MongoDB-compatible interface integrated directly into the Prisme.ai platform:Collections Organization
- Each collection contains related documents
- Collections are created automatically when used
- No schema definition is required
- Each workspace has its own collection namespace
Document Structure
- Each document has a unique
_idfield - Documents can have any structure
- Fields can contain various data types
- Nested objects and arrays are supported
- Documents in the same collection can have different structures
Data Operations
- Commands follow MongoDB syntax and patterns
- Results are returned in standard formats
- Operations are executed in a secure environment
- Performance is optimized for common use cases
Integration
- Direct usage in automations
- Connection to AI agents through tools
- Data exchange with other platform components
- Role-based access control
⚖️ MongoDB vs PostgreSQL Differences
- $in Operator
- NULL vs $ne
- Array Queries
- Array order on updates
- Nested JSON Array Queries
- Upserts
- $addToSet
-
MongoDB:
$in: []matches nothing. -
PostgreSQL:
$in: []matches everything!\Always check your input array before running$inqueries on PostgreSQL.
🛠️ Configuring a Collection Schema
- The array type only supports text arrays
- Use json type for both objects and arrays of objects
- Non-nullable properties must be set on inserts and upserts. Otherwise the given query will fail
string, text, date, time, datetime, number, double, float, integer, decimal, boolean, uint8array, array, enum, enumArray, json, blob, time🔄 Changing a Property Type
Changing thetype of a property that already holds data means converting
every existing row. The default conversion fails as soon as one value does not
fit the new type: a text column switched to json chokes on the first row
that is not valid JSON.
Text converted to json automatically
On PostgreSQL, a property now declaredjson whose column is still text is
converted without declaring anything, when the platform knows how its rows
were written. It decides from what the collection’s schema said before the
update:
array (text array) is always converted, each
array becoming the same JSON array.
{"en":"Hello"} is
read as the object { en: 'Hello' } from then on. Until it is converted, a
json property stored in a text column is read as the raw text.workspaces.collections.notMigrated event in the
activity feed: the column, the reason, and the migration to declare
(skipped[].howTo). The collection
keeps working on its previous schema until you declare it, as described below.
Declaring a migration
Declare a migration next to your properties to choose how the existing values are converted, or to convert a column the platform left alone. Add it to the configuration of the Collection instance:from.
The migration runs before the schema is synchronized, and in the same
transaction: if the synchronization then fails (a new unique index on
duplicate values, for instance), the conversion is rolled back with it and the
column keeps its previous type.
It only runs once, by itself
Thefrom list is a guard checked against the column’s current type in the
database. Once the column has been converted, from no longer matches and the
migration is skipped.
The conversion rewrites the table while locking it. If the table stays locked
by something else for more than 5 seconds (COLLECTIONS_MIGRATION_LOCK_TIMEOUT_MS
on a self-hosted runtime), the conversion gives up rather than block every
request on the collection, and runs again at the next update.
Converting to json
auto is what you want for a column that accumulated both plain text written
before the type change and JSON written after it. Use lenient only for a
column whose values were all written as JSON.
auto and lenient work on every supported PostgreSQL version; they are
faster from PostgreSQL 16.Following what happened
A migration that actually converts data emits aworkspaces.collections.migrated event in the activity feed, reporting the
column, the type it had, the type it became, the number of rows rewritten
(rows, an estimate when rowsEstimated is true), how many of them now read
as a number, a boolean or null instead of a string (retyped, with lenient
only) and how long it took. A migration that matches nothing emits nothing.
If a declared migration fails, the collection keeps working on its previous
schema and the workspaces.collections.notMigrated event tells you which column
refused and why (failed), so the failure is visible immediately instead of
surfacing weeks later. A conversion undone because the rest of the schema update
failed after it is listed in rolledBack.
Checking and converting from an automation
Without access to the database, two functions of the collections module let an automation of your workspace do the same, on its own collections only:getSchemaDriftlists the collections whose table no longer matches their configuration: a column of the wrong type, a column that was never created.runSchemaMigrationsconverts the columns of one collection with the migrations you give it, then synchronizes the collection with its configuration, exactly like an update of the Collection instance. WithdryRun: true, it only tells you what it would convert, and how.
plan.planned (the cast, the number of rows, retyped), then run the
same call without dryRun: the conversion emits the same
workspaces.collections.migrated event, and getSchemaDrift no longer lists
the collection. To keep the migration for the instances you have not converted
yet, declare it in the configuration as well.
A few rules:
- declare the property
jsonin the configuration first: only conversions tojsonbofjsonproperties are accepted, since the synchronization brings every other column back to its declared type; - run it once, from a manual or one-shot automation: each call synchronizes the
collection, even with nothing to convert, and never take the
migrationsfrom a request payload; - PostgreSQL only: on MongoDB there are no column types, so no drift.
Basic Operations
Let’s explore the core operations you can perform with Collection:Inserting Data
Inserting Data
_id values.Finding Data
Finding Data
Updating Data
Updating Data
$set operator to only update given fields without removing other fields already existing in the matched record :Upserts
Upserts
Deleting Data
Deleting Data
Distinct values
Distinct values
Aggregation Operations
Aggregation Operations
sum, avg, count, max, min.max and min work on any orderable field type: numbers, datetimes (BSON dates and ISO 8601 strings), and strings (lexicographic order).find + sort + limit):Find pagination & fields selection
Find pagination & fields selection
You can then choose which page you are interested in using options.page, starting at 1 for the first page :
Advanced Features
Collection includes several advanced features that enable sophisticated data management:Indexing
- Single-field indexes
- Compound indexes
- Text indexes for full-text search
- Unique indexes for constraint enforcement
Transactions
- Atomic operations across multiple documents
- Rollback on error
- Consistent reads within a transaction
- Isolation levels
Geospatial
- GeoJSON format support
- Proximity queries
- Geospatial indexing
- Area containment queries
Schema Validation
- JSON Schema validation
- Custom validation rules
- Validation actions (error or warning)
- Field restriction
Common Use Cases
Collection enables a wide range of use cases:User Management
- User profiles
- Preferences
- Activity history
- Authentication data
Content Management
- Articles and posts
- Product information
- Media metadata
- Categorization and tagging
Workflow State
- Status tracking
- Approval flows
- Stage information
- Audit history
Data Collection
- Survey responses
- Application data
- Contact requests
- Registration information
Integration with Prisme.ai Products
Collection works seamlessly with other Prisme.ai products:- Knowledges
- Builder
- Custom Code
- API Integrations
- Store metadata about knowledge base documents
- Track usage patterns and popular queries
- Maintain user feedback on responses
- Save and manage test results
Example: Contact Management System
Here’s an example of using Collection to build a contact management system:Define Data Structure
- Contacts collection for individual contacts
- Companies collection for organization information
- Interactions collection for communication history
- Tags collection for categorization
Create Storage Operations
Implement Query Operations
Create User Interface
- Contact list view
- Contact detail view
- Add/edit contact forms
- Search and filtering
Implement Business Logic
- Duplicate detection
- Contact merging
- Import/export capabilities
- Notification system
Best Practices
Follow these recommendations to get the most from Collection:Data Modeling
Data Modeling
- Use descriptive collection names
- Choose between embedding and referencing based on access patterns
- Keep document size reasonable (under 1MB when possible)
- Normalize data when it changes frequently
- Denormalize data to optimize common queries
- Use consistent field names across collections
Query Optimization
Query Optimization
- Create indexes for frequently queried fields
- Write specific queries that use indexes
- Limit the number of documents returned
- Avoid complex regex patterns when possible
- Use aggregation for data processing, not application code
Data Validation
Data Validation
- Validate input data before storage
- Consider using schema validation for critical collections
- Implement application-level validation for complex rules
- Use unique indexes to prevent duplicates
- Include creation and update timestamps
- Maintain audit trails for sensitive data
Security Considerations
Security Considerations
- Apply proper access controls
- Validate input to prevent injection attacks
- Don’t store sensitive data without encryption
- Implement appropriate backup strategies
- Audit access to sensitive collections
- Follow the principle of least privilege
Limitations and Considerations
When using Collection, be aware of these considerations:- Document Size: Individual documents are limited to 16MB
- Nested Depth: Deep nesting of objects can impact performance
- Query Complexity: Very complex queries may have performance implications
- Transaction Limits: Transactions have time and size limitations
- Indexing Overhead: Indexes improve query performance but increase storage requirements and write overhead
- Consistency Model: Collection uses an eventually consistent model in some scenarios