AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents
TypeScript ai-agentai-agent-toolsai-agentsai-agents-frameworkmcpmcp-servermcp-toolsmcpsn8n-alternativeno-code-automationworkflowworkflow-automationworkflows
feat(mongodb): let AI agents query, write and manage collections and indexes (#17070)
Kishan Parmar9e662aa07cc9
diff --git a/bun.lock b/bun.lockindex 8bf08eb7478..e7a26f1af20 100644--- a/bun.lock+++ b/bun.lock@@ -6287,7 +6287,7 @@},"packages/pieces/community/mongodb": {"name": "@activepieces/piece-mongodb",- "version": "0.1.7",+ "version": "0.2.0","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*",diff --git a/packages/pieces/community/mongodb/package.json b/packages/pieces/community/mongodb/package.jsonindex 4db46df58eb..eb4d08ab34f 100644--- a/packages/pieces/community/mongodb/package.json+++ b/packages/pieces/community/mongodb/package.json@@ -1,6 +1,6 @@{"name": "@activepieces/piece-mongodb",- "version": "0.1.7",+ "version": "0.2.0","main": "./dist/src/index.js","types": "./dist/src/index.d.ts","dependencies": {diff --git a/packages/pieces/community/mongodb/src/index.ts b/packages/pieces/community/mongodb/src/index.tsindex 843e7507ab7..57337169cfd 100644--- a/packages/pieces/community/mongodb/src/index.ts+++ b/packages/pieces/community/mongodb/src/index.ts@@ -1,99 +1,30 @@-import {- PiecePropValueSchema,- createPiece,- PieceAuth,- Property,-} from '@activepieces/pieces-framework';-import { AppConnectionType, PieceCategory } from '@activepieces/pieces-framework';-import { propsValidation } from '@activepieces/pieces-common';-import * as z from 'zod/mini'--import actions from './lib/actions';-import { mongodbConnect } from './lib/common';--export const mongodbAuth = PieceAuth.CustomAuth({- validate: async ({ auth }) => {- try {- await validateAuth(auth);- return {- valid: true,- };- } catch (e) {- return {- valid: false,- error: (e as Error)?.message,- };- }- },- props: {- host: Property.ShortText({- displayName: 'Host',- required: true,- description:- 'The hostname or address of the MongoDB server (e.g., localhost:27017 or cluster.example.mongodb.net)',- }),- useAtlasUrl: Property.Checkbox({- displayName: 'Use MongoDB Atlas URL Format',- description:- 'Enable this if connecting to MongoDB Atlas (uses mongodb+srv:// protocol)',- required: true,- defaultValue: false,- }),- database: Property.ShortText({- displayName: 'Database',- required: false,- description:- 'The MongoDB database to connect to (can be specified per action if left empty)',- }),- username: Property.ShortText({- displayName: 'Username',- required: true,- description: 'The username to use for connecting to the MongoDB server',- }),- password: PieceAuth.SecretText({- displayName: 'Password',- description: 'The password to use to identify at the MongoDB server',- required: true,- }),- authSource: Property.ShortText({- displayName: 'Auth Source',- required: false,- description: 'The database to authenticate against (default: admin)',- defaultValue: 'admin',- }),- },- required: true,-});--const validateAuth = async (auth: PiecePropValueSchema<typeof mongodbAuth>) => {- await propsValidation.validateZod(auth, {- host: z.string().check(z.minLength(1)),- useAtlasUrl: z.boolean(),- database: z.optional(z.string()),- username: z.string().check(z.minLength(1)),- password: z.optional(z.string()),- authSource: z.optional(z.string()),- });-- const client = await mongodbConnect({- props: auth,- type: AppConnectionType.CUSTOM_AUTH,- });-- await client.db('admin').command({ ping: 1 });-- await client.close();-- console.log('MongoDB validation successful');-};+import { createPiece, PieceCategory } from '@activepieces/pieces-framework';+import { mongodbAuth } from './lib/auth';+import { findDocumentsAction } from './lib/actions/find-documents';+import { insertDocumentsAction } from './lib/actions/insert-documents';+import { updateDocumentsAction } from './lib/actions/update-documents';+import { deleteDocumentsAction } from './lib/actions/delete-documents';+import { findAndUpdateDocumentsAction } from './lib/actions/find-and-update-documents';+import { findAndReplaceDocumentsAction } from './lib/actions/find-and-replace-documents';+import { aggregateDocumentsAction } from './lib/actions/aggregate-documents';+import { mongodbAiActions } from './lib/actions/ai';export const mongodb = createPiece({displayName: 'MongoDB',auth: mongodbAuth,- minimumSupportedRelease: '0.36.1',+ minimumSupportedRelease: '0.88.2',categories: [PieceCategory.DEVELOPER_TOOLS],logoUrl: 'https://cdn.activepieces.com/pieces/mongodb.png',authors: ['denieler'],- actions,+ actions: [+ findDocumentsAction,+ insertDocumentsAction,+ updateDocumentsAction,+ deleteDocumentsAction,+ findAndUpdateDocumentsAction,+ findAndReplaceDocumentsAction,+ aggregateDocumentsAction,+ ...mongodbAiActions,+ ],triggers: [],});diff --git a/packages/pieces/community/mongodb/src/lib/actions.ts b/packages/pieces/community/mongodb/src/lib/actions.tsdeleted file mode 100644index be68568ea01..00000000000--- a/packages/pieces/community/mongodb/src/lib/actions.ts+++ /dev/null@@ -1,17 +0,0 @@-import findDocuments from './actions/find-documents';-import insertDocuments from './actions/insert-documents';-import updateDocuments from './actions/update-documents';-import deleteDocuments from './actions/delete-documents';-import findAndUpdateDocuments from './actions/find-and-update-documents';-import findAndReplaceDocuments from './actions/find-and-replace-documents';-import aggregateDocuments from './actions/aggregate-documents';--export default [- findDocuments,- insertDocuments,- updateDocuments,- deleteDocuments,- findAndUpdateDocuments,- findAndReplaceDocuments,- aggregateDocuments,-];diff --git a/packages/pieces/community/mongodb/src/lib/actions/aggregate-documents.ts b/packages/pieces/community/mongodb/src/lib/actions/aggregate-documents.tsindex ecd5f373376..0547f6533b5 100644--- a/packages/pieces/community/mongodb/src/lib/actions/aggregate-documents.ts+++ b/packages/pieces/community/mongodb/src/lib/actions/aggregate-documents.ts@@ -1,20 +1,21 @@import { createAction, Property } from '@activepieces/pieces-framework';-import { mongodbAuth } from '../..';+import { mongodbAuth } from '../auth';import { aggregateDocumentsOutputSchema } from '../output-schemas';-import { mongodbCommon, mongodbConnect } from '../common';+import { mongodbClient } from '../common/client';+import { mongodbProps } from '../common/props';-export default createAction({+export const aggregateDocumentsAction = createAction({auth: mongodbAuth,name: 'aggregate_documents',classification: 'WRITE',displayName: 'Aggregate Documents',description: 'Perform aggregation operations on documents in a collection',- audience: 'both',+ audience: 'human',outputSchema: aggregateDocumentsOutputSchema,aiMetadata: { description: 'Runs a MongoDB aggregation pipeline over a collection and returns the resulting documents. Use for grouping, joining, computed fields, faceting, or any read that goes beyond a simple find filter. The pipeline must be an array of stage objects (e.g. $match, $group, $sort). Read-only and idempotent for read-only pipelines (avoid write stages like $out/$merge).', idempotent: true },props: {- database: mongodbCommon.database,- collection: mongodbCommon.collection(),+ database: mongodbProps.database({ required: false }),+ collection: mongodbProps.collection({ required: true }),pipeline: Property.Json({displayName: 'Aggregation Pipeline',description: 'Array of aggregation stages (e.g., [{"$match": {"status": "active"}}, {"$group": {"_id": "$category", "count": {"$sum": 1}}}])',@@ -22,8 +23,7 @@ export default createAction({}),},async run(context) {-- const client = await mongodbConnect(context.auth);+ const client = await mongodbClient.create({ auth: context.auth });try {if (!context.propsValue.collection) {@@ -34,8 +34,6 @@ export default createAction({throw new Error('Aggregation pipeline is required');}- // Use the database from auth- // Use the database from props or authconst databaseName = context.propsValue.database || context.auth.props.database;if (!databaseName) {throw new Error('Database is required. Please specify it in the connection settings or in this action.');diff --git a/packages/pieces/community/mongodb/src/lib/actions/ai/aggregate-documents.ts b/packages/pieces/community/mongodb/src/lib/actions/ai/aggregate-documents.tsnew file mode 100644index 00000000000..9025710dbe6--- /dev/null+++ b/packages/pieces/community/mongodb/src/lib/actions/ai/aggregate-documents.ts@@ -0,0 +1,49 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { BSON } from 'mongodb';+import type { Document } from 'mongodb';+import { mongodbAuth } from '../../auth';+import { mongodbAiProps } from '../../common/ai-props';+import { mongodbClient } from '../../common/client';+import { mongodbUtils } from '../../common/utils';+import { aggregateDocumentsOutputSchema } from '../../output-schemas';++export const aggregateDocumentsAiAction = createAction({+ auth: mongodbAuth,+ name: 'mongodb_aggregate_documents',+ displayName: 'Aggregate Documents',+ description: 'Run an aggregation pipeline on a collection.',+ audience: 'ai',+ classification: 'WRITE',+ outputSchema: aggregateDocumentsOutputSchema,+ aiMetadata: {+ description: 'Runs an aggregation pipeline (an array of stages such as $match, $group, $sort, $lookup) over a collection and returns the resulting documents. Use it for grouping, joins, computed fields or totals; use Find Documents for a plain filtered read. Stages $out and $merge write to another collection, so leave them out unless asked.',+ idempotent: false,+ },+ props: {+ database: mongodbAiProps.database({ required: false }),+ collection: mongodbAiProps.collection({ required: true }),+ pipeline: Property.Json({+ displayName: 'Pipeline',+ description: 'Array of stages, e.g. [{"$match": {"status": "active"}}, {"$group": {"_id": "$category", "total": {"$sum": 1}}}]. Use {"$oid": "<24-hex id>"} for an ObjectId and {"$date": "<ISO date>"} for a date.',+ required: true,+ }),+ },+ async run(context) {+ const pipeline: Document | Document[] = BSON.EJSON.deserialize(context.propsValue.pipeline);+ if (!Array.isArray(pipeline)) {+ throw new Error('"pipeline" must be an array of stage objects.');+ }+ const databaseName = mongodbUtils.databaseName({ auth: context.auth, database: context.propsValue.database });+ const client = await mongodbClient.create({ auth: context.auth });+ try {+ const result = await client+ .db(databaseName)+ .collection(context.propsValue.collection)+ .aggregate(pipeline)+ .toArray();+ return { result, count: result.length };+ } finally {+ await client.close();+ }+ },+});diff --git a/packages/pieces/community/mongodb/src/lib/actions/ai/bulk-write.ts b/packages/pieces/community/mongodb/src/lib/actions/ai/bulk-write.tsnew file mode 100644index 00000000000..b46d5f36d1c--- /dev/null+++ b/packages/pieces/community/mongodb/src/lib/actions/ai/bulk-write.ts@@ -0,0 +1,104 @@+import { createAction, Property, tryCatch } from '@activepieces/pieces-framework';+import { BSON, MongoBulkWriteError } from 'mongodb';+import type { AnyBulkWriteOperation, Document } from 'mongodb';+import { mongodbAuth } from '../../auth';+import { mongodbAiProps } from '../../common/ai-props';+import { mongodbClient } from '../../common/client';+import { mongodbUtils } from '../../common/utils';+import { mongodbBulkWriteOutputSchema } from '../../output-schemas';++export const bulkWriteAction = createAction({+ auth: mongodbAuth,+ name: 'mongodb_bulk_write',+ outputSchema: mongodbBulkWriteOutputSchema,+ displayName: 'Bulk Write',+ description: 'Run up to 500 single-document inserts, updates, replaces and deletes in one call.',+ audience: 'ai',+ classification: 'DESTRUCTIVE',+ aiMetadata: {+ description: 'Runs a list of single-document operations (insertOne, updateOne, replaceOne, deleteOne) on one collection in one call, e.g. to upsert many records that each need different values. At most 500 operations; updateMany and deleteMany are not allowed. Ordered by default: it stops at the first failure and the error says how many operations ran. Not idempotent.',+ idempotent: false,+ },+ props: {+ database: mongodbAiProps.database({ required: false }),+ collection: mongodbAiProps.collection({ required: true }),+ operations: Property.Json({+ displayName: 'Operations',+ description: 'Array of operations, each an object with exactly one key: {"insertOne": {"document": {...}}}, {"updateOne": {"filter": {...}, "update": {"$set": {...}}, "upsert": true}}, {"replaceOne": {"filter": {...}, "replacement": {...}}} or {"deleteOne": {"filter": {...}}}. Use {"$oid": "<24-hex id>"} for an ObjectId and {"$date": "<ISO date>"} for a date.',+ required: true,+ }),+ ordered: Property.StaticDropdown({+ displayName: 'Ordered',+ description: 'true: run in order and stop at the first failure. false: run every operation and report all failures. Defaults to true.',+ required: false,+ options: {+ options: [+ { label: 'True', value: 'true' },+ { label: 'False', value: 'false' },+ ],+ },+ }),+ },+ async run(context) {+ const parsed: Document | Document[] = BSON.EJSON.deserialize(context.propsValue.operations);+ if (!Array.isArray(parsed) || parsed.length === 0 || parsed.length > MAX_OPERATIONS) {+ throw new Error(`"operations" must be an array of 1 to ${MAX_OPERATIONS} operations.`);+ }+ const operations = parsed.map((operation, index) => toOperation({ operation, index }));+ const databaseName = mongodbUtils.databaseName({ auth: context.auth, database: context.propsValue.database });+ const client = await mongodbClient.create({ auth: context.auth });+ try {+ const { data: result, error } = await tryCatch(() =>+ client+ .db(databaseName)+ .collection(context.propsValue.collection)+ .bulkWrite(operations, { ordered: context.propsValue.ordered !== 'false' }),+ );+ if (error instanceof MongoBulkWriteError) {+ const failures = [error.writeErrors].flat().map((writeError) => `operation ${writeError.index}: ${writeError.errmsg}`);+ throw new Error(+ `Bulk write failed at ${failures.join('; ')}. Applied before the failure: ${error.insertedCount} inserted, ${error.modifiedCount} modified, ${error.upsertedCount} upserted, ${error.deletedCount} deleted.`,+ );+ }+ if (error) {+ throw error;+ }+ return {+ insertedCount: result.insertedCount,+ matchedCount: result.matchedCount,+ modifiedCount: result.modifiedCount,+ deletedCount: result.deletedCount,+ upsertedCount: result.upsertedCount,+ insertedIds: result.insertedIds,+ upsertedIds: result.upsertedIds,+ };+ } finally {+ await client.close();+ }+ },+});++function toOperation({ operation, index }: { operation: Document; index: number }): AnyBulkWriteOperation<Document> {+ const keys = Object.keys(operation);+ if (keys.length !== 1) {+ throw new Error(`Operation ${index} must have exactly one key: insertOne, updateOne, replaceOne or deleteOne.`);+ }+ const model = operation[keys[0]];+ switch (keys[0]) {+ case 'insertOne':+ return { insertOne: model };+ case 'updateOne':+ return { updateOne: model };+ case 'replaceOne':+ return { replaceOne: model };+ case 'deleteOne':+ if (!model?.filter || Object.keys(model.filter).length === 0) {+ throw new Error(`Operation ${index} (deleteOne) needs a non-empty filter.`);+ }+ return { deleteOne: model };+ default:+ throw new Error(`Operation ${index} uses "${keys[0]}"; only insertOne, updateOne, replaceOne and deleteOne are allowed.`);+ }+}++const MAX_OPERATIONS = 500;diff --git a/packages/pieces/community/mongodb/src/lib/actions/ai/count-documents.ts b/packages/pieces/community/mongodb/src/lib/actions/ai/count-documents.tsnew file mode 100644index 00000000000..e8926fca490--- /dev/null+++ b/packages/pieces/community/mongodb/src/lib/actions/ai/count-documents.ts@@ -0,0 +1,41 @@+import { createAction } from '@activepieces/pieces-framework';+import { BSON } from 'mongodb';+import type { Document } from 'mongodb';+import { mongodbAuth } from '../../auth';+import { mongodbAiProps } from '../../common/ai-props';+import { mongodbClient } from '../../common/client';+import { mongodbUtils } from '../../common/utils';+import { mongodbCountDocumentsOutputSchema } from '../../output-schemas';++export const countDocumentsAction = createAction({+ auth: mongodbAuth,+ name: 'mongodb_count_documents',+ outputSchema: mongodbCountDocumentsOutputSchema,+ displayName: 'Count Documents',+ description: 'Count the documents in a collection that match a filter.',+ audience: 'ai',+ classification: 'SEARCH',+ aiMetadata: {+ description: 'Returns the exact number of documents in a collection that match a filter, without returning the documents. Pick it over Find Documents when only the number matters. The collection comes from List Collections.',+ idempotent: true,+ },+ props: {+ database: mongodbAiProps.database({ required: false }),+ collection: mongodbAiProps.collection({ required: true }),+ filter: mongodbAiProps.filter({ required: false }),+ },+ async run(context) {+ const filter: Document = BSON.EJSON.deserialize(context.propsValue.filter ?? {});+ const databaseName = mongodbUtils.databaseName({ auth: context.auth, database: context.propsValue.database });+ const client = await mongodbClient.create({ auth: context.auth });+ try {+ const count = await client+ .db(databaseName)+ .collection(context.propsValue.collection)+ .countDocuments(filter);+ return { count };+ } finally {+ await client.close();+ }+ },+});diff --git a/packages/pieces/community/mongodb/src/lib/actions/ai/create-collection.ts b/packages/pieces/community/mongodb/src/lib/actions/ai/create-collection.tsnew file mode 100644index 00000000000..46d34616733--- /dev/null+++ b/packages/pieces/community/mongodb/src/lib/actions/ai/create-collection.ts@@ -0,0 +1,37 @@+import { createAction } from '@activepieces/pieces-framework';+import { mongodbAuth } from '../../auth';+import { mongodbAiProps } from '../../common/ai-props';+import { mongodbClient } from '../../common/client';+import { mongodbUtils } from '../../common/utils';+import { mongodbCreateCollectionOutputSchema } from '../../output-schemas';++export const createCollectionAction = createAction({+ auth: mongodbAuth,+ name: 'mongodb_create_collection',+ outputSchema: mongodbCreateCollectionOutputSchema,+ displayName: 'Create Collection',+ description: 'Create a new collection in a database.',+ audience: 'ai',+ classification: 'WRITE',+ aiMetadata: {+ description: 'Creates an empty collection. On MongoDB 7.0 and later, creating a collection that already exists succeeds without changing it; older servers return an error. Inserting into a missing collection also creates it, so this is only needed for an empty one.',+ idempotent: true,+ },+ props: {+ database: mongodbAiProps.database({ required: false }),+ collection: mongodbAiProps.collection({+ required: true,+ description: 'Name of the new collection, e.g. "orders".',+ }),+ },+ async run(context) {+ const databaseName = mongodbUtils.databaseName({ auth: context.auth, database: context.propsValue.database });+ const client = await mongodbClient.create({ auth: context.auth });+ try {+ const result = await client.db(databaseName).command({ create: context.propsValue.collection });+ return { ...result, database: databaseName, collection: context.propsValue.collection };+ } finally {+ await client.close();+ }+ },+});diff --git a/packages/pieces/community/mongodb/src/lib/actions/ai/create-index.ts b/packages/pieces/community/mongodb/src/lib/actions/ai/create-index.tsnew file mode 100644index 00000000000..c3d165143f1--- /dev/null+++ b/packages/pieces/community/mongodb/src/lib/actions/ai/create-index.ts@@ -0,0 +1,64 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import type { Document } from 'mongodb';+import { mongodbAuth } from '../../auth';+import { mongodbAiProps } from '../../common/ai-props';+import { mongodbClient } from '../../common/client';+import { mongodbUtils } from '../../common/utils';+import { mongodbCreateIndexOutputSchema } from '../../output-schemas';++export const createIndexAction = createAction({+ auth: mongodbAuth,+ name: 'mongodb_create_index',+ outputSchema: mongodbCreateIndexOutputSchema,+ displayName: 'Create Index',+ description: 'Create an index on a collection.',+ audience: 'ai',+ classification: 'WRITE',+ aiMetadata: {+ description: 'Creates an index on one or more fields of a collection and returns its name. Repeating the call with the same keys and options is a no-op; the same keys with different options fail. A unique index fails if existing documents already hold duplicate values.',+ idempotent: true,+ },+ props: {+ database: mongodbAiProps.database({ required: false }),+ collection: mongodbAiProps.collection({ required: true }),+ keys: Property.Json({+ displayName: 'Keys',+ description: 'Fields and direction, e.g. {"email": 1} or {"lastName": 1, "createdAt": -1}. Use "text" for a text index.',+ required: true,+ }),+ indexName: Property.ShortText({+ displayName: 'Index Name',+ description: 'Name for the index. Defaults to a name MongoDB builds from the keys, e.g. "email_1".',+ required: false,+ }),+ unique: Property.StaticDropdown({+ displayName: 'Unique',+ description: 'Whether the indexed values must be unique. Defaults to false.',+ required: false,+ options: {+ options: [+ { label: 'True', value: 'true' },+ { label: 'False', value: 'false' },+ ],+ },+ }),+ },+ async run(context) {+ const { indexName, unique } = context.propsValue;+ const keys: Document = context.propsValue.keys;+ const databaseName = mongodbUtils.databaseName({ auth: context.auth, database: context.propsValue.database });+ const client = await mongodbClient.create({ auth: context.auth });+ try {+ const name = await client+ .db(databaseName)+ .collection(context.propsValue.collection)+ .createIndex(keys, {+ ...(indexName ? { name: indexName } : {}),+ ...(unique ? { unique: unique === 'true' } : {}),+ });+ return { indexName: name };+ } finally {+ await client.close();+ }+ },+});diff --git a/packages/pieces/community/mongodb/src/lib/actions/ai/delete-documents.ts b/packages/pieces/community/mongodb/src/lib/actions/ai/delete-documents.tsnew file mode 100644index 00000000000..9b1bab17d51--- /dev/null+++ b/packages/pieces/community/mongodb/src/lib/actions/ai/delete-documents.ts@@ -0,0 +1,44 @@+import { createAction } from '@activepieces/pieces-framework';+import { BSON } from 'mongodb';+import type { Document } from 'mongodb';+import { mongodbAuth } from '../../auth';+import { mongodbAiProps } from '../../common/ai-props';+import { mongodbClient } from '../../common/client';+import { mongodbUtils } from '../../common/utils';+import { deleteDocumentsOutputSchema } from '../../output-schemas';++export const deleteDocumentsAiAction = createAction({+ auth: mongodbAuth,+ name: 'mongodb_delete_documents',+ displayName: 'Delete Documents',+ description: 'Permanently delete every document that matches a filter.',+ audience: 'ai',+ classification: 'DESTRUCTIVE',+ outputSchema: deleteDocumentsOutputSchema,+ aiMetadata: {+ description: 'Permanently deletes every document matching a filter and returns how many were deleted; there is no undo. An empty filter is rejected; to delete every document on purpose pass {"_id": {"$exists": true}}. Use Count Documents first to check how many match.',+ idempotent: false,+ },+ props: {+ database: mongodbAiProps.database({ required: false }),+ collection: mongodbAiProps.collection({ required: true }),+ filter: mongodbAiProps.filter({ required: true }),+ },+ async run(context) {+ const filter: Document = BSON.EJSON.deserialize(context.propsValue.filter);+ if (Object.keys(filter).length === 0) {+ throw new Error('"filter" is empty and would delete every document. Pass {"_id": {"$exists": true}} to delete them all on purpose.');+ }+ const databaseName = mongodbUtils.databaseName({ auth: context.auth, database: context.propsValue.database });+ const client = await mongodbClient.create({ auth: context.auth });+ try {+ const result = await client+ .db(databaseName)+ .collection(context.propsValue.collection)+ .deleteMany(filter);+ return { deletedCount: result.deletedCount };+ } finally {+ await client.close();+ }+ },+});diff --git a/packages/pieces/community/mongodb/src/lib/actions/ai/delete-one-document.ts b/packages/pieces/community/mongodb/src/lib/actions/ai/delete-one-document.tsnew file mode 100644index 00000000000..feb48b569b9--- /dev/null+++ b/packages/pieces/community/mongodb/src/lib/actions/ai/delete-one-document.ts@@ -0,0 +1,44 @@+import { createAction } from '@activepieces/pieces-framework';+import { BSON } from 'mongodb';+import type { Document } from 'mongodb';+import { mongodbAuth } from '../../auth';+import { mongodbAiProps } from '../../common/ai-props';+import { mongodbClient } from '../../common/client';+import { mongodbUtils } from '../../common/utils';+import { deleteDocumentsOutputSchema } from '../../output-schemas';++export const deleteOneDocumentAction = createAction({+ auth: mongodbAuth,+ name: 'mongodb_delete_one_document',+ displayName: 'Delete One Document',+ description: 'Permanently delete the first document that matches a filter.',+ audience: 'ai',+ classification: 'DESTRUCTIVE',+ outputSchema: deleteDocumentsOutputSchema,+ aiMetadata: {+ description: 'Permanently deletes at most one document, the first that matches the filter; there is no undo. Pick it over Delete Documents when exactly one record should go, e.g. by _id ({"_id": {"$oid": "<id>"}}). An empty filter is rejected.',+ idempotent: false,+ },+ props: {+ database: mongodbAiProps.database({ required: false }),+ collection: mongodbAiProps.collection({ required: true }),+ filter: mongodbAiProps.filter({ required: true }),+ },+ async run(context) {+ const filter: Document = BSON.EJSON.deserialize(context.propsValue.filter);+ if (Object.keys(filter).length === 0) {+ throw new Error('"filter" is empty and would delete an arbitrary document. Pass a filter that identifies the document.');+ }+ const databaseName = mongodbUtils.databaseName({ auth: context.auth, database: context.propsValue.database });+ const client = await mongodbClient.create({ auth: context.auth });+ try {+ const result = await client+ .db(databaseName)+ .collection(context.propsValue.collection)+ .deleteOne(filter);+ return { deletedCount: result.deletedCount };+ } finally {+ await client.close();+ }+ },+});diff --git a/packages/pieces/community/mongodb/src/lib/actions/ai/distinct-values.ts b/packages/pieces/community/mongodb/src/lib/actions/ai/distinct-values.tsnew file mode 100644index 00000000000..d26daaf946c--- /dev/null+++ b/packages/pieces/community/mongodb/src/lib/actions/ai/distinct-values.ts@@ -0,0 +1,57 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { BSON } from 'mongodb';+import type { Document } from 'mongodb';+import { mongodbAuth } from '../../auth';+import { mongodbAiProps } from '../../common/ai-props';+import { mongodbClient } from '../../common/client';+import { mongodbUtils } from '../../common/utils';+import { mongodbDistinctValuesOutputSchema } from '../../output-schemas';++export const distinctValuesAction = createAction({+ auth: mongodbAuth,+ name: 'mongodb_distinct_values',+ outputSchema: mongodbDistinctValuesOutputSchema,+ displayName: 'Get Distinct Values',+ description: 'Get the distinct values of a field across matching documents.',+ audience: 'ai',+ classification: 'SEARCH',+ aiMetadata: {+ description: 'Returns the unique values of one field across the documents that match a filter; array fields contribute each element, an explicit null counts as a value, and documents without the field are skipped. Use it to discover categories, statuses or other enumerations in a collection. Returns at most the limit (default 100, max 1000).',+ idempotent: true,+ },+ props: {+ database: mongodbAiProps.database({ required: false }),+ collection: mongodbAiProps.collection({ required: true }),+ field: Property.ShortText({+ displayName: 'Field',+ description: 'Field path to read, e.g. "status" or "address.city".',+ required: true,+ }),+ filter: mongodbAiProps.filter({ required: false }),+ limit: mongodbAiProps.limit({ required: false }),+ },+ async run(context) {+ const { field } = context.propsValue;+ const filter: Document = BSON.EJSON.deserialize(context.propsValue.filter ?? {});+ const databaseName = mongodbUtils.databaseName({ auth: context.auth, database: context.propsValue.database });+ const client = await mongodbClient.create({ auth: context.auth });+ try {+ const groups = await client+ .db(databaseName)+ .collection(context.propsValue.collection)+ .aggregate([+ { $match: filter },+ { $unwind: { path: `$${field}`, preserveNullAndEmptyArrays: true } },+ { $match: { [field]: { $exists: true } } },+ { $group: { _id: `$${field}` } },+ { $sort: { _id: 1 } },+ { $limit: mongodbUtils.limit({ value: context.propsValue.limit }) },+ ])+ .toArray();+ const values = groups.map((group) => group['_id']);+ return { values, count: values.length };+ } finally {+ await client.close();+ }+ },+});diff --git a/packages/pieces/community/mongodb/src/lib/actions/ai/drop-collection.ts b/packages/pieces/community/mongodb/src/lib/actions/ai/drop-collection.tsnew file mode 100644index 00000000000..da6eaa5b437--- /dev/null+++ b/packages/pieces/community/mongodb/src/lib/actions/ai/drop-collection.ts@@ -0,0 +1,34 @@+import { createAction } from '@activepieces/pieces-framework';+import { mongodbAuth } from '../../auth';+import { mongodbAiProps } from '../../common/ai-props';+import { mongodbClient } from '../../common/client';+import { mongodbUtils } from '../../common/utils';+import { mongodbDropCollectionOutputSchema } from '../../output-schemas';++export const dropCollectionAction = createAction({+ auth: mongodbAuth,+ name: 'mongodb_drop_collection',+ outputSchema: mongodbDropCollectionOutputSchema,+ displayName: 'Drop Collection',+ description: 'Permanently delete a collection with all its documents and indexes.',+ audience: 'ai',+ classification: 'DESTRUCTIVE',+ aiMetadata: {+ description: 'Permanently deletes a collection with every document and index in it; there is no undo. Use Delete Documents instead to remove only some documents. The collection comes from List Collections.',+ idempotent: false,+ },+ props: {+ database: mongodbAiProps.database({ required: false }),+ collection: mongodbAiProps.collection({ required: true }),+ },+ async run(context) {+ const databaseName = mongodbUtils.databaseName({ auth: context.auth, database: context.propsValue.database });+ const client = await mongodbClient.create({ auth: context.auth });+ try {+ const result = await client.db(databaseName).command({ drop: context.propsValue.collection });+ return { ...result, database: databaseName, collection: context.propsValue.collection };+ } finally {+ await client.close();+ }+ },+});diff --git a/packages/pieces/community/mongodb/src/lib/actions/ai/drop-index.ts b/packages/pieces/community/mongodb/src/lib/actions/ai/drop-index.tsnew file mode 100644index 00000000000..0148b9dc655--- /dev/null+++ b/packages/pieces/community/mongodb/src/lib/actions/ai/drop-index.ts@@ -0,0 +1,41 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { mongodbAuth } from '../../auth';+import { mongodbAiProps } from '../../common/ai-props';+import { mongodbClient } from '../../common/client';+import { mongodbUtils } from '../../common/utils';+import { mongodbDropIndexOutputSchema } from '../../output-schemas';++export const dropIndexAction = createAction({+ auth: mongodbAuth,+ name: 'mongodb_drop_index',+ outputSchema: mongodbDropIndexOutputSchema,+ displayName: 'Drop Index',+ description: 'Remove an index from a collection.',+ audience: 'ai',+ classification: 'DESTRUCTIVE',+ aiMetadata: {+ description: 'Removes one index from a collection by name; documents are not touched. The name comes from List Indexes; the default "_id_" index cannot be dropped.',+ idempotent: false,+ },+ props: {+ database: mongodbAiProps.database({ required: false }),+ collection: mongodbAiProps.collection({ required: true }),+ indexName: Property.ShortText({+ displayName: 'Index Name',+ description: 'Name of the index, e.g. "email_1". Use List Indexes to find it.',+ required: true,+ }),+ },+ async run(context) {+ const databaseName = mongodbUtils.databaseName({ auth: context.auth, database: context.propsValue.database });+ const client = await mongodbClient.create({ auth: context.auth });+ try {+ return await client+ .db(databaseName)+ .collection(context.propsValue.collection)+ .dropIndex(context.propsValue.indexName);+ } finally {+ await client.close();+ }+ },+});diff --git a/packages/pieces/community/mongodb/src/lib/actions/ai/find-and-replace-document.ts b/packages/pieces/community/mongodb/src/lib/actions/ai/find-and-replace-document.tsnew file mode 100644index 00000000000..762325c90b8--- /dev/null+++ b/packages/pieces/community/mongodb/src/lib/actions/ai/find-and-replace-document.ts@@ -0,0 +1,66 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { BSON } from 'mongodb';+import type { Document } from 'mongodb';+import { mongodbAuth } from '../../auth';+import { mongodbAiProps } from '../../common/ai-props';+import { mongodbApi } from '../../common/api';+import { mongodbClient } from '../../common/client';+import { mongodbUtils } from '../../common/utils';+import { findAndReplaceDocumentsOutputSchema } from '../../output-schemas';++export const findAndReplaceDocumentAiAction = createAction({+ auth: mongodbAuth,+ name: 'mongodb_find_and_replace_document',+ displayName: 'Find and Replace Document',+ description: 'Replace the first document that matches a filter with a new document.',+ audience: 'ai',+ classification: 'WRITE',+ outputSchema: findAndReplaceDocumentsOutputSchema,+ aiMetadata: {+ description: 'Overwrites the first document matching a filter with a whole new document (fields not in the replacement are removed; _id is kept) and returns it as it was before or after. Use Update Documents to change only some fields. Supports upsert. Not idempotent.',+ idempotent: false,+ },+ props: {+ database: mongodbAiProps.database({ required: false }),+ collection: mongodbAiProps.collection({ required: true }),+ filter: mongodbAiProps.filter({ required: true }),+ replacement: Property.Json({+ displayName: 'Replacement Document',+ description: 'The full new document, without update operators, e.g. {"name": "Ada", "status": "active"}.',+ required: true,+ }),+ upsert: mongodbAiProps.upsert({ required: false }),+ returnDocument: Property.StaticDropdown({+ displayName: 'Return Document',+ description: 'Return the document as it was before or after the replacement. Defaults to after.',+ required: false,+ options: {+ options: [+ { label: 'Before', value: 'before' },+ { label: 'After', value: 'after' },+ ],+ },+ }),+ },+ async run(context) {+ const returnDocument = context.propsValue.returnDocument ?? 'after';+ if (returnDocument !== 'before' && returnDocument !== 'after') {+ throw new Error('"returnDocument" must be "before" or "after".');+ }+ const filter: Document = BSON.EJSON.deserialize(context.propsValue.filter);+ const replacement: Document = BSON.EJSON.deserialize(context.propsValue.replacement);+ const databaseName = mongodbUtils.databaseName({ auth: context.auth, database: context.propsValue.database });+ const client = await mongodbClient.create({ auth: context.auth });+ try {+ return await mongodbApi.findAndReplaceDocument({+ collection: client.db(databaseName).collection(context.propsValue.collection),+ filter,+ replacement,+ upsert: context.propsValue.upsert === 'true',+ returnDocumentPreference: returnDocument,+ });+ } finally {+ await client.close();+ }+ },+});diff --git a/packages/pieces/community/mongodb/src/lib/actions/ai/find-and-update-documents.ts b/packages/pieces/community/mongodb/src/lib/actions/ai/find-and-update-documents.tsnew file mode 100644index 00000000000..59f5c1ac40e--- /dev/null+++ b/packages/pieces/community/mongodb/src/lib/actions/ai/find-and-update-documents.ts@@ -0,0 +1,58 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { BSON } from 'mongodb';+import type { Document } from 'mongodb';+import { mongodbAuth } from '../../auth';+import { mongodbAiProps } from '../../common/ai-props';+import { mongodbApi } from '../../common/api';+import { mongodbClient } from '../../common/client';+import { mongodbUtils } from '../../common/utils';+import { findAndUpdateDocumentsOutputSchema } from '../../output-schemas';++export const findAndUpdateDocumentsAiAction = createAction({+ auth: mongodbAuth,+ name: 'mongodb_find_and_update_documents',+ displayName: 'Find and Update Documents',+ description: 'Update every document that matches a filter and return the updated documents.',+ audience: 'ai',+ classification: 'WRITE',+ outputSchema: findAndUpdateDocumentsOutputSchema,+ aiMetadata: {+ description: 'Applies update operators to every document matching a filter, then re-reads the documents that match the same filter and returns them with the counts. Pick it over Update Documents when the updated documents are needed; if the update changes a field the filter uses, the re-read can miss them. Not idempotent.',+ idempotent: false,+ },+ props: {+ database: mongodbAiProps.database({ required: false }),+ collection: mongodbAiProps.collection({ required: true }),+ filter: mongodbAiProps.filter({ required: true }),+ update: mongodbAiProps.update({ required: true }),+ upsert: mongodbAiProps.upsert({ required: false }),+ returnUpdated: Property.StaticDropdown({+ displayName: 'Return Updated Documents',+ description: 'Return the documents after the update. Defaults to true.',+ required: false,+ options: {+ options: [+ { label: 'True', value: 'true' },+ { label: 'False', value: 'false' },+ ],+ },+ }),+ },+ async run(context) {+ const filter: Document = BSON.EJSON.deserialize(context.propsValue.filter);+ const update: Document = BSON.EJSON.deserialize(context.propsValue.update);+ const databaseName = mongodbUtils.databaseName({ auth: context.auth, database: context.propsValue.database });+ const client = await mongodbClient.create({ auth: context.auth });+ try {+ return await mongodbApi.findAndUpdateDocuments({+ collection: client.db(databaseName).collection(context.propsValue.collection),+ filter,+ update,+ upsert: context.propsValue.upsert === 'true',+ returnUpdated: context.propsValue.returnUpdated !== 'false',+ });+ } finally {+ await client.close();+ }+ },+});diff --git a/packages/pieces/community/mongodb/src/lib/actions/ai/find-documents.ts b/packages/pieces/community/mongodb/src/lib/actions/ai/find-documents.tsnew file mode 100644index 00000000000..9ac1c67aac1--- /dev/null+++ b/packages/pieces/community/mongodb/src/lib/actions/ai/find-documents.ts@@ -0,0 +1,57 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { BSON } from 'mongodb';+import type { Document } from 'mongodb';+import { mongodbAuth } from '../../auth';+import { mongodbAiProps } from '../../common/ai-props';+import { mongodbClient } from '../../common/client';+import { mongodbUtils } from '../../common/utils';+import { findDocumentsOutputSchema } from '../../output-schemas';++export const findDocumentsAiAction = createAction({+ auth: mongodbAuth,+ name: 'mongodb_find_documents',+ displayName: 'Find Documents',+ description: 'Find documents in a collection.',+ audience: 'ai',+ classification: 'SEARCH',+ outputSchema: findDocumentsOutputSchema,+ aiMetadata: {+ description: 'Reads documents from a collection that match a filter, with projection, sort, skip and limit (default 100, max 1000). Use Find One Document for a single document by _id, Count Documents when only the number matters, and Aggregate Documents for grouping or joins. The collection comes from List Collections.',+ idempotent: true,+ },+ props: {+ database: mongodbAiProps.database({ required: false }),+ collection: mongodbAiProps.collection({ required: true }),+ filter: mongodbAiProps.filter({ required: false }),+ projection: mongodbAiProps.projection({ required: false }),+ sort: Property.Json({+ displayName: 'Sort',+ description: 'Sort order, 1 ascending and -1 descending, e.g. {"createdAt": -1}.',+ required: false,+ }),+ skip: Property.Number({+ displayName: 'Skip',+ description: 'Number of matching documents to skip, for paging. Defaults to 0.',+ required: false,+ }),+ limit: mongodbAiProps.limit({ required: false }),+ },+ async run(context) {+ const { projection, skip } = context.propsValue;+ const filter: Document = BSON.EJSON.deserialize(context.propsValue.filter ?? {});+ const sort: Document = context.propsValue.sort ?? {};+ const databaseName = mongodbUtils.databaseName({ auth: context.auth, database: context.propsValue.database });+ const client = await mongodbClient.create({ auth: context.auth });+ try {+ const documents = await client+ .db(databaseName)+ .collection(context.propsValue.collection)+ .find(filter, { projection, sort, skip })+ .limit(mongodbUtils.limit({ value: context.propsValue.limit }))+ .toArray();+ return { documents, count: documents.length };+ } finally {+ await client.close();+ }+ },+});diff --git a/packages/pieces/community/mongodb/src/lib/actions/ai/find-one-document.ts b/packages/pieces/community/mongodb/src/lib/actions/ai/find-one-document.tsnew file mode 100644index 00000000000..5717a8b47f4--- /dev/null+++ b/packages/pieces/community/mongodb/src/lib/actions/ai/find-one-document.ts@@ -0,0 +1,62 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { BSON, ObjectId } from 'mongodb';+import type { Document } from 'mongodb';+import { mongodbAuth } from '../../auth';+import { mongodbAiProps } from '../../common/ai-props';+import { mongodbClient } from '../../common/client';+import { mongodbUtils } from '../../common/utils';+import { mongodbFindOneDocumentOutputSchema } from '../../output-schemas';++export const findOneDocumentAction = createAction({+ auth: mongodbAuth,+ name: 'mongodb_find_one_document',+ outputSchema: mongodbFindOneDocumentOutputSchema,+ displayName: 'Find One Document',+ description: 'Get a single document by its _id or by a filter.',+ audience: 'ai',+ classification: 'READ',+ aiMetadata: {+ description: 'Returns one document, looked up by its _id (as returned by Find Documents or Insert Documents) or by the first match of a filter; pass exactly one of the two. A 24-character hex _id matches both an ObjectId and the plain string. The document is null when nothing matches.',+ idempotent: true,+ },+ props: {+ database: mongodbAiProps.database({ required: false }),+ collection: mongodbAiProps.collection({ required: true }),+ documentId: Property.ShortText({+ displayName: 'Document ID',+ description: 'The document _id, e.g. "65f1c0a2b3d4e5f6a7b8c9d0". Leave empty when using Filter.',+ required: false,+ }),+ filter: mongodbAiProps.filter({+ required: false,+ description: 'MongoDB query object, e.g. {"email": "[email protected]"}; the first match is returned. Leave empty when using Document ID.',+ }),+ projection: mongodbAiProps.projection({ required: false }),+ },+ async run(context) {+ const { documentId, filter, projection } = context.propsValue;+ const hasFilter = filter !== undefined && Object.keys(filter).length > 0;+ if (Boolean(documentId) === hasFilter) {+ throw new Error('Provide exactly one of "documentId" or "filter".');+ }+ const query: Document = documentId ? idQuery({ documentId }) : BSON.EJSON.deserialize(filter ?? {});+ const databaseName = mongodbUtils.databaseName({ auth: context.auth, database: context.propsValue.database });+ const client = await mongodbClient.create({ auth: context.auth });+ try {+ const document = await client+ .db(databaseName)+ .collection(context.propsValue.collection)+ .findOne(query, { projection });+ return { found: document !== null, document };+ } finally {+ await client.close();+ }+ },+});++function idQuery({ documentId }: { documentId: string }): Document {+ if (ObjectId.isValid(documentId) && documentId.length === 24) {+ return { _id: { $in: [new ObjectId(documentId), documentId] } };+ }+ return { _id: documentId };+}diff --git a/packages/pieces/community/mongodb/src/lib/actions/ai/index.ts b/packages/pieces/community/mongodb/src/lib/actions/ai/index.tsnew file mode 100644index 00000000000..271afc264c9--- /dev/null+++ b/packages/pieces/community/mongodb/src/lib/actions/ai/index.ts@@ -0,0 +1,43 @@+import { bulkWriteAction } from './bulk-write';+import { deleteOneDocumentAction } from './delete-one-document';+import { updateOneDocumentAction } from './update-one-document';+import { aggregateDocumentsAiAction } from './aggregate-documents';+import { deleteDocumentsAiAction } from './delete-documents';+import { findAndReplaceDocumentAiAction } from './find-and-replace-document';+import { findAndUpdateDocumentsAiAction } from './find-and-update-documents';+import { findDocumentsAiAction } from './find-documents';+import { insertDocumentsAiAction } from './insert-documents';+import { updateDocumentsAiAction } from './update-documents';+import { countDocumentsAction } from './count-documents';+import { createCollectionAction } from './create-collection';+import { createIndexAction } from './create-index';+import { distinctValuesAction } from './distinct-values';+import { dropCollectionAction } from './drop-collection';+import { dropIndexAction } from './drop-index';+import { findOneDocumentAction } from './find-one-document';+import { listCollectionsAction } from './list-collections';+import { listDatabasesAction } from './list-databases';+import { listIndexesAction } from './list-indexes';++export const mongodbAiActions = [+ listDatabasesAction,+ listCollectionsAction,+ countDocumentsAction,+ distinctValuesAction,+ findDocumentsAiAction,+ findOneDocumentAction,+ insertDocumentsAiAction,+ updateDocumentsAiAction,+ updateOneDocumentAction,+ findAndUpdateDocumentsAiAction,+ findAndReplaceDocumentAiAction,+ deleteDocumentsAiAction,+ deleteOneDocumentAction,+ bulkWriteAction,+ aggregateDocumentsAiAction,+ createCollectionAction,+ dropCollectionAction,+ listIndexesAction,+ createIndexAction,+ dropIndexAction,+];diff --git a/packages/pieces/community/mongodb/src/lib/actions/ai/insert-documents.ts b/packages/pieces/community/mongodb/src/lib/actions/ai/insert-documents.tsnew file mode 100644index 00000000000..7a8b91c6d70--- /dev/null+++ b/packages/pieces/community/mongodb/src/lib/actions/ai/insert-documents.ts@@ -0,0 +1,50 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { BSON } from 'mongodb';+import type { Document } from 'mongodb';+import { mongodbAuth } from '../../auth';+import { mongodbAiProps } from '../../common/ai-props';+import { mongodbClient } from '../../common/client';+import { mongodbUtils } from '../../common/utils';+import { insertDocumentsOutputSchema } from '../../output-schemas';++export const insertDocumentsAiAction = createAction({+ auth: mongodbAuth,+ name: 'mongodb_insert_documents',+ displayName: 'Insert Documents',+ description: 'Insert one or more documents into a collection.',+ audience: 'ai',+ classification: 'WRITE',+ outputSchema: insertDocumentsOutputSchema,+ aiMetadata: {+ description: 'Inserts one document (an object) or several (an array of objects) into a collection, creating the collection if it does not exist, and returns the new _id values. Each call adds new documents, so repeating it creates duplicates.',+ idempotent: false,+ },+ props: {+ database: mongodbAiProps.database({ required: false }),+ collection: mongodbAiProps.collection({ required: true }),+ documents: Property.Json({+ displayName: 'Documents',+ description: 'One document object, or an array of document objects, e.g. [{"name": "Ada"}, {"name": "Alan"}]. Use {"$date": "<ISO date>"} for a date and {"$oid": "<24-hex id>"} for an ObjectId.',+ required: true,+ }),+ },+ async run(context) {+ const documents: Document | Document[] = BSON.EJSON.deserialize(context.propsValue.documents);+ const databaseName = mongodbUtils.databaseName({ auth: context.auth, database: context.propsValue.database });+ const client = await mongodbClient.create({ auth: context.auth });+ try {+ const collection = client.db(databaseName).collection(context.propsValue.collection);+ if (Array.isArray(documents)) {+ if (documents.length === 0) {+ return { insertedCount: 0, insertedIds: {} };+ }+ const result = await collection.insertMany(documents);+ return { insertedCount: result.insertedCount, insertedIds: result.insertedIds };+ }+ const result = await collection.insertOne(documents);+ return { insertedId: result.insertedId, acknowledged: result.acknowledged };+ } finally {+ await client.close();+ }+ },+});diff --git a/packages/pieces/community/mongodb/src/lib/actions/ai/list-collections.ts b/packages/pieces/community/mongodb/src/lib/actions/ai/list-collections.tsnew file mode 100644index 00000000000..b0d3633ea31--- /dev/null+++ b/packages/pieces/community/mongodb/src/lib/actions/ai/list-collections.ts@@ -0,0 +1,33 @@+import { createAction } from '@activepieces/pieces-framework';+import { mongodbAuth } from '../../auth';+import { mongodbAiProps } from '../../common/ai-props';+import { mongodbClient } from '../../common/client';+import { mongodbUtils } from '../../common/utils';+import { mongodbListCollectionsOutputSchema } from '../../output-schemas';++export const listCollectionsAction = createAction({+ auth: mongodbAuth,+ name: 'mongodb_list_collections',+ outputSchema: mongodbListCollectionsOutputSchema,+ displayName: 'List Collections',+ description: 'List the collections in a database.',+ audience: 'ai',+ classification: 'SEARCH',+ aiMetadata: {+ description: 'Lists the collections and views in a database, with their type and options. Use it to find a collection name for the other MongoDB actions; the database comes from List Databases or the connection.',+ idempotent: true,+ },+ props: {+ database: mongodbAiProps.database({ required: false }),+ },+ async run(context) {+ const databaseName = mongodbUtils.databaseName({ auth: context.auth, database: context.propsValue.database });+ const client = await mongodbClient.create({ auth: context.auth });+ try {+ const collections = await client.db(databaseName).listCollections().toArray();+ return { collections, count: collections.length };+ } finally {+ await client.close();+ }+ },+});diff --git a/packages/pieces/community/mongodb/src/lib/actions/ai/list-databases.ts b/packages/pieces/community/mongodb/src/lib/actions/ai/list-databases.tsnew file mode 100644index 00000000000..11c419a52f9--- /dev/null+++ b/packages/pieces/community/mongodb/src/lib/actions/ai/list-databases.ts@@ -0,0 +1,27 @@+import { createAction } from '@activepieces/pieces-framework';+import { mongodbAuth } from '../../auth';+import { mongodbClient } from '../../common/client';+import { mongodbListDatabasesOutputSchema } from '../../output-schemas';++export const listDatabasesAction = createAction({+ auth: mongodbAuth,+ name: 'mongodb_list_databases',+ outputSchema: mongodbListDatabasesOutputSchema,+ displayName: 'List Databases',+ description: 'List the databases on the MongoDB server.',+ audience: 'ai',+ classification: 'SEARCH',+ aiMetadata: {+ description: 'Lists the databases the connection can see, with their size on disk. Use it to find a database name for the other MongoDB actions.',+ idempotent: true,+ },+ props: {},+ async run(context) {+ const client = await mongodbClient.create({ auth: context.auth });+ try {+ return await client.db('admin').admin().listDatabases();+ } finally {+ await client.close();+ }+ },+});diff --git a/packages/pieces/community/mongodb/src/lib/actions/ai/list-indexes.ts b/packages/pieces/community/mongodb/src/lib/actions/ai/list-indexes.tsnew file mode 100644index 00000000000..72d8c8bb856--- /dev/null+++ b/packages/pieces/community/mongodb/src/lib/actions/ai/list-indexes.ts@@ -0,0 +1,38 @@+import { createAction } from '@activepieces/pieces-framework';+import { mongodbAuth } from '../../auth';+import { mongodbAiProps } from '../../common/ai-props';+import { mongodbClient } from '../../common/client';+import { mongodbUtils } from '../../common/utils';+import { mongodbListIndexesOutputSchema } from '../../output-schemas';++export const listIndexesAction = createAction({+ auth: mongodbAuth,+ name: 'mongodb_list_indexes',+ outputSchema: mongodbListIndexesOutputSchema,+ displayName: 'List Indexes',+ description: 'List the indexes on a collection.',+ audience: 'ai',+ classification: 'SEARCH',+ aiMetadata: {+ description: 'Lists the indexes on a collection with their name, keys and options such as unique. Use it before Create Index to avoid duplicates, or to get the name Drop Index needs.',+ idempotent: true,+ },+ props: {+ database: mongodbAiProps.database({ required: false }),+ collection: mongodbAiProps.collection({ required: true }),+ },+ async run(context) {+ const databaseName = mongodbUtils.databaseName({ auth: context.auth, database: context.propsValue.database });+ const client = await mongodbClient.create({ auth: context.auth });+ try {+ const indexes = await client+ .db(databaseName)+ .collection(context.propsValue.collection)+ .listIndexes()+ .toArray();+ return { indexes, count: indexes.length };+ } finally {+ await client.close();+ }+ },+});diff --git a/packages/pieces/community/mongodb/src/lib/actions/ai/update-documents.ts b/packages/pieces/community/mongodb/src/lib/actions/ai/update-documents.tsnew file mode 100644index 00000000000..e95ab6adb67--- /dev/null+++ b/packages/pieces/community/mongodb/src/lib/actions/ai/update-documents.ts@@ -0,0 +1,49 @@+import { createAction } from '@activepieces/pieces-framework';+import { BSON } from 'mongodb';+import type { Document } from 'mongodb';+import { mongodbAuth } from '../../auth';+import { mongodbAiProps } from '../../common/ai-props';+import { mongodbClient } from '../../common/client';+import { mongodbUtils } from '../../common/utils';+import { updateDocumentsOutputSchema } from '../../output-schemas';++export const updateDocumentsAiAction = createAction({+ auth: mongodbAuth,+ name: 'mongodb_update_documents',+ displayName: 'Update Documents',+ description: 'Update every document that matches a filter.',+ audience: 'ai',+ classification: 'WRITE',+ outputSchema: updateDocumentsOutputSchema,+ aiMetadata: {+ description: 'Applies update operators such as $set or $inc to every document matching a filter and returns the matched and modified counts; with upsert it inserts a document when nothing matches. Use Find and Update Documents to also get the updated documents back. Not idempotent: $inc and upsert change state on each call.',+ idempotent: false,+ },+ props: {+ database: mongodbAiProps.database({ required: false }),+ collection: mongodbAiProps.collection({ required: true }),+ filter: mongodbAiProps.filter({ required: true }),+ update: mongodbAiProps.update({ required: true }),+ upsert: mongodbAiProps.upsert({ required: false }),+ },+ async run(context) {+ const filter: Document = BSON.EJSON.deserialize(context.propsValue.filter);+ const update: Document = BSON.EJSON.deserialize(context.propsValue.update);+ const databaseName = mongodbUtils.databaseName({ auth: context.auth, database: context.propsValue.database });+ const client = await mongodbClient.create({ auth: context.auth });+ try {+ const result = await client+ .db(databaseName)+ .collection(context.propsValue.collection)+ .updateMany(filter, update, { upsert: context.propsValue.upsert === 'true' });+ return {+ matchedCount: result.matchedCount,+ modifiedCount: result.modifiedCount,+ upsertedCount: result.upsertedCount,+ upsertedId: result.upsertedId,+ };+ } finally {+ await client.close();+ }+ },+});diff --git a/packages/pieces/community/mongodb/src/lib/actions/ai/update-one-document.ts b/packages/pieces/community/mongodb/src/lib/actions/ai/update-one-document.tsnew file mode 100644index 00000000000..8410523f326--- /dev/null+++ b/packages/pieces/community/mongodb/src/lib/actions/ai/update-one-document.ts@@ -0,0 +1,49 @@+import { createAction } from '@activepieces/pieces-framework';+import { BSON } from 'mongodb';+import type { Document } from 'mongodb';+import { mongodbAuth } from '../../auth';+import { mongodbAiProps } from '../../common/ai-props';+import { mongodbClient } from '../../common/client';+import { mongodbUtils } from '../../common/utils';+import { updateDocumentsOutputSchema } from '../../output-schemas';++export const updateOneDocumentAction = createAction({+ auth: mongodbAuth,+ name: 'mongodb_update_one_document',+ displayName: 'Update One Document',+ description: 'Update the first document that matches a filter.',+ audience: 'ai',+ classification: 'WRITE',+ outputSchema: updateDocumentsOutputSchema,+ aiMetadata: {+ description: 'Applies update operators such as $set or $inc to at most one document, the first that matches the filter; with upsert it inserts one when nothing matches. Pick it over Update Documents when exactly one record should change, e.g. by _id ({"_id": {"$oid": "<id>"}}). Not idempotent: $inc and upsert change state on each call.',+ idempotent: false,+ },+ props: {+ database: mongodbAiProps.database({ required: false }),+ collection: mongodbAiProps.collection({ required: true }),+ filter: mongodbAiProps.filter({ required: true }),+ update: mongodbAiProps.update({ required: true }),+ upsert: mongodbAiProps.upsert({ required: false }),+ },+ async run(context) {+ const filter: Document = BSON.EJSON.deserialize(context.propsValue.filter);+ const update: Document = BSON.EJSON.deserialize(context.propsValue.update);+ const databaseName = mongodbUtils.databaseName({ auth: context.auth, database: context.propsValue.database });+ const client = await mongodbClient.create({ auth: context.auth });+ try {+ const result = await client+ .db(databaseName)+ .collection(context.propsValue.collection)+ .updateOne(filter, update, { upsert: context.propsValue.upsert === 'true' });+ return {+ matchedCount: result.matchedCount,+ modifiedCount: result.modifiedCount,+ upsertedCount: result.upsertedCount,+ upsertedId: result.upsertedId,+ };+ } finally {+ await client.close();+ }+ },+});diff --git a/packages/pieces/community/mongodb/src/lib/actions/delete-documents.ts b/packages/pieces/community/mongodb/src/lib/actions/delete-documents.tsindex 6c2ad7de4dc..a6808b60ddb 100644--- a/packages/pieces/community/mongodb/src/lib/actions/delete-documents.ts+++ b/packages/pieces/community/mongodb/src/lib/actions/delete-documents.ts@@ -1,20 +1,21 @@import { createAction, Property } from '@activepieces/pieces-framework';-import { mongodbAuth } from '../..';+import { mongodbAuth } from '../auth';import { deleteDocumentsOutputSchema } from '../output-schemas';-import { mongodbCommon, mongodbConnect } from '../common';+import { mongodbClient } from '../common/client';+import { mongodbProps } from '../common/props';-export default createAction({+export const deleteDocumentsAction = createAction({auth: mongodbAuth,name: 'delete_documents',classification: 'DESTRUCTIVE',displayName: 'Delete Documents',description: 'Delete documents from a collection',- audience: 'both',+ audience: 'human',outputSchema: deleteDocumentsOutputSchema,aiMetadata: { description: 'Removes every document matching a filter from a MongoDB collection via deleteMany. Use to delete records in bulk; an empty filter would match and delete all documents in the collection, so scope the filter carefully. The filter is required. Mutating and destructive; repeating the call deletes whatever now matches, so it is not idempotent.', idempotent: false },props: {- database: mongodbCommon.database,- collection: mongodbCommon.collection(),+ database: mongodbProps.database({ required: false }),+ collection: mongodbProps.collection({ required: true }),filter: Property.Json({displayName: 'Filter',description: 'MongoDB query to select documents to delete (e.g., {"status": "archived"})',@@ -22,7 +23,7 @@ export default createAction({}),},async run(context) {- const client = await mongodbConnect(context.auth);+ const client = await mongodbClient.create({ auth: context.auth });try {if (!context.propsValue.collection) {diff --git a/packages/pieces/community/mongodb/src/lib/actions/find-and-replace-documents.ts b/packages/pieces/community/mongodb/src/lib/actions/find-and-replace-documents.tsindex 9d757f22006..10aeea1ed2f 100644--- a/packages/pieces/community/mongodb/src/lib/actions/find-and-replace-documents.ts+++ b/packages/pieces/community/mongodb/src/lib/actions/find-and-replace-documents.ts@@ -1,20 +1,22 @@import { createAction, Property } from '@activepieces/pieces-framework';-import { mongodbAuth } from '../..';+import { mongodbAuth } from '../auth';import { findAndReplaceDocumentsOutputSchema } from '../output-schemas';-import { mongodbCommon, mongodbConnect } from '../common';+import { mongodbApi } from '../common/api';+import { mongodbClient } from '../common/client';+import { mongodbProps } from '../common/props';-export default createAction({+export const findAndReplaceDocumentsAction = createAction({auth: mongodbAuth,name: 'find_and_replace_documents',classification: 'WRITE',displayName: 'Find and Replace Documents',description: 'Replace documents that match a filter with a new document',- audience: 'both',+ audience: 'human',outputSchema: findAndReplaceDocumentsOutputSchema,aiMetadata: { description: 'Replaces the first document matching a filter with an entirely new document via replaceOne (the whole document is overwritten, not patched), and can return either the before or after version. Choose this over Update Documents when swapping a full document rather than applying field-level operators. Filter and replacement are required; supports upsert. Mutating and not idempotent.', idempotent: false },props: {- database: mongodbCommon.database,- collection: mongodbCommon.collection(),+ database: mongodbProps.database({ required: false }),+ collection: mongodbProps.collection({ required: true }),filter: Property.Json({displayName: 'Filter',description: 'MongoDB query to select documents to replace (e.g., {"_id": "123"})',@@ -45,7 +47,7 @@ export default createAction({}),},async run(context) {- const client = await mongodbConnect(context.auth);+ const client = await mongodbClient.create({ auth: context.auth });try {if (!context.propsValue.collection) {@@ -72,35 +74,13 @@ export default createAction({const upsert = context.propsValue.upsert || false;const returnDocumentPreference = context.propsValue.returnDocument || 'after';- let beforeDocument = null;- if (returnDocumentPreference === 'before') {- beforeDocument = await collection.findOne(filter);- }-- const replaceResult = await collection.replaceOne(+ return await mongodbApi.findAndReplaceDocument({+ collection,filter,replacement,- {- upsert- }- );-- let afterDocument = null;- if (returnDocumentPreference === 'after' || (!beforeDocument && replaceResult.matchedCount > 0)) {- const query = replaceResult.upsertedId- ? { _id: replaceResult.upsertedId }- : filter;- afterDocument = await collection.findOne(query);- }-- const document = returnDocumentPreference === 'before' ? beforeDocument : afterDocument;-- return {- matchedCount: replaceResult.matchedCount,- modifiedCount: replaceResult.modifiedCount,- upsertedId: replaceResult.upsertedId,- document,- };+ upsert,+ returnDocumentPreference,+ });} finally {await client.close();}diff --git a/packages/pieces/community/mongodb/src/lib/actions/find-and-update-documents.ts b/packages/pieces/community/mongodb/src/lib/actions/find-and-update-documents.tsindex 43fa95d2aaf..bc2dcb264d9 100644--- a/packages/pieces/community/mongodb/src/lib/actions/find-and-update-documents.ts+++ b/packages/pieces/community/mongodb/src/lib/actions/find-and-update-documents.ts@@ -1,20 +1,22 @@import { createAction, Property } from '@activepieces/pieces-framework';-import { mongodbAuth } from '../..';+import { mongodbAuth } from '../auth';import { findAndUpdateDocumentsOutputSchema } from '../output-schemas';-import { mongodbCommon, mongodbConnect } from '../common';+import { mongodbApi } from '../common/api';+import { mongodbClient } from '../common/client';+import { mongodbProps } from '../common/props';-export default createAction({+export const findAndUpdateDocumentsAction = createAction({auth: mongodbAuth,name: 'find_and_update_documents',classification: 'WRITE',displayName: 'Find and Update Documents',description: 'Find documents and update them, returning the updated documents',- audience: 'both',+ audience: 'human',outputSchema: findAndUpdateDocumentsOutputSchema,aiMetadata: { description: 'Applies MongoDB update operators to all documents matching a filter via updateMany, then optionally re-reads and returns the matched documents in their post-update state. Choose this over plain Update Documents when the agent needs to see the resulting documents, not just counts. Filter and update are required; supports upsert. Not idempotent: it mutates state and operators like $inc compound on each call.', idempotent: false },props: {- database: mongodbCommon.database,- collection: mongodbCommon.collection(),+ database: mongodbProps.database({ required: false }),+ collection: mongodbProps.collection({ required: true }),filter: Property.Json({displayName: 'Filter',description: 'MongoDB query to select documents to update (e.g., {"status": "pending"})',@@ -39,7 +41,7 @@ export default createAction({}),},async run(context) {- const client = await mongodbConnect(context.auth);+ const client = await mongodbClient.create({ auth: context.auth });try {if (!context.propsValue.collection) {@@ -66,20 +68,13 @@ export default createAction({const upsert = context.propsValue.upsert || false;const returnUpdated = context.propsValue.returnUpdated !== false;- const updateResult = await collection.updateMany(filter, update, { upsert });-- let documents: Record<string, unknown>[] = [];- if (returnUpdated) {- documents = await collection.find(filter).toArray();- }-- return {- matchedCount: updateResult.matchedCount,- modifiedCount: updateResult.modifiedCount,- upsertedCount: updateResult.upsertedCount,- upsertedId: updateResult.upsertedId,- documents: returnUpdated ? documents : undefined,- };+ return await mongodbApi.findAndUpdateDocuments({+ collection,+ filter,+ update,+ upsert,+ returnUpdated,+ });} finally {await client.close();}diff --git a/packages/pieces/community/mongodb/src/lib/actions/find-documents.ts b/packages/pieces/community/mongodb/src/lib/actions/find-documents.tsindex 18cdc48e761..b1ac449ccb5 100644--- a/packages/pieces/community/mongodb/src/lib/actions/find-documents.ts+++ b/packages/pieces/community/mongodb/src/lib/actions/find-documents.ts@@ -1,20 +1,22 @@import { createAction, Property } from '@activepieces/pieces-framework';-import { mongodbAuth } from '../..';+import type { Document } from 'mongodb';+import { mongodbAuth } from '../auth';import { findDocumentsOutputSchema } from '../output-schemas';-import { mongodbCommon, mongodbConnect } from '../common';+import { mongodbClient } from '../common/client';+import { mongodbProps } from '../common/props';-export default createAction({+export const findDocumentsAction = createAction({auth: mongodbAuth,name: 'find_documents',classification: 'SEARCH',displayName: 'Find Documents',description: 'Find documents in a collection',- audience: 'both',+ audience: 'human',outputSchema: findDocumentsOutputSchema,aiMetadata: { description: 'Reads documents from a MongoDB collection, optionally filtered by a query, with projection, sort, limit, and skip. An empty query returns all documents in the collection; pass a query object to filter to matching documents. Use to look up or list records when you need raw documents rather than aggregated results. Requires a collection (and a database, from the action or the connection). Read-only and idempotent.', idempotent: true },props: {- database: mongodbCommon.database,- collection: mongodbCommon.collection(),+ database: mongodbProps.database({ required: false }),+ collection: mongodbProps.collection({ required: true }),query: Property.Json({displayName: 'Query',description: 'MongoDB query to filter documents (e.g., {"status": "active"})',@@ -46,7 +48,7 @@ export default createAction({}),},async run(context) {- const client = await mongodbConnect(context.auth);+ const client = await mongodbClient.create({ auth: context.auth });try {if (!context.propsValue.collection) {@@ -62,17 +64,14 @@ export default createAction({const query = context.propsValue.query || {};const projection = context.propsValue.projection || {};- const sort = context.propsValue.sort || {};+ const sort: Document = context.propsValue.sort || {};const limit = context.propsValue.limit || 0;const skip = context.propsValue.skip || 0;let cursor = collection.find(query, { projection });if (Object.keys(sort).length > 0) {- // MongoDB sort needs to be handled with care due to typing constraints- // We'll use a type assertion but in a safer way than 'any'- // The MongoDB driver expects a document with field names and sort direction (1 or -1)- cursor = cursor.sort(sort as Record<string, 1 | -1>);+ cursor = cursor.sort(sort);}if (skip > 0) {diff --git a/packages/pieces/community/mongodb/src/lib/actions/insert-documents.ts b/packages/pieces/community/mongodb/src/lib/actions/insert-documents.tsindex 4155883e3b4..49a7b017ca0 100644--- a/packages/pieces/community/mongodb/src/lib/actions/insert-documents.ts+++ b/packages/pieces/community/mongodb/src/lib/actions/insert-documents.ts@@ -1,20 +1,21 @@import { createAction, Property } from '@activepieces/pieces-framework';-import { mongodbAuth } from '../..';+import { mongodbAuth } from '../auth';import { insertDocumentsOutputSchema } from '../output-schemas';-import { mongodbCommon, mongodbConnect } from '../common';+import { mongodbClient } from '../common/client';+import { mongodbProps } from '../common/props';-export default createAction({+export const insertDocumentsAction = createAction({auth: mongodbAuth,name: 'insert_documents',classification: 'WRITE',displayName: 'Insert Documents',description: 'Insert one or more documents into a collection',- audience: 'both',+ audience: 'human',outputSchema: insertDocumentsOutputSchema,aiMetadata: { description: 'Inserts new documents into a MongoDB collection; accepts either a single document object or an array of documents. Use to add records. Not idempotent: each call creates new documents with fresh _id values, so repeating it appends duplicates.', idempotent: false },props: {- database: mongodbCommon.database,- collection: mongodbCommon.collection(),+ database: mongodbProps.database({ required: false }),+ collection: mongodbProps.collection({ required: true }),documents: Property.Json({displayName: 'Documents',description: 'Document(s) to insert. Can be a single document object or an array of documents.',@@ -22,7 +23,7 @@ export default createAction({}),},async run(context) {- const client = await mongodbConnect(context.auth);+ const client = await mongodbClient.create({ auth: context.auth });try {if (!context.propsValue.collection) {@@ -44,7 +45,6 @@ export default createAction({let result;if (Array.isArray(documents)) {- // Insert many documentsif (documents.length === 0) {return { insertedCount: 0, insertedIds: [] };}@@ -54,7 +54,6 @@ export default createAction({insertedIds: result.insertedIds,};} else {- // Insert a single documentresult = await collection.insertOne(documents);return {insertedId: result.insertedId,diff --git a/packages/pieces/community/mongodb/src/lib/actions/update-documents.ts b/packages/pieces/community/mongodb/src/lib/actions/update-documents.tsindex 489e9b5aea5..abfa61ed799 100644--- a/packages/pieces/community/mongodb/src/lib/actions/update-documents.ts+++ b/packages/pieces/community/mongodb/src/lib/actions/update-documents.ts@@ -1,20 +1,21 @@import { createAction, Property } from '@activepieces/pieces-framework';-import { mongodbAuth } from '../..';+import { mongodbAuth } from '../auth';import { updateDocumentsOutputSchema } from '../output-schemas';-import { mongodbCommon, mongodbConnect } from '../common';+import { mongodbClient } from '../common/client';+import { mongodbProps } from '../common/props';-export default createAction({+export const updateDocumentsAction = createAction({auth: mongodbAuth,name: 'update_documents',classification: 'WRITE',displayName: 'Update Documents',description: 'Update multiple documents in a collection',- audience: 'both',+ audience: 'human',outputSchema: updateDocumentsOutputSchema,aiMetadata: { description: 'Applies MongoDB update operators (e.g. $set, $inc) to every document matching a filter via updateMany; optionally upserts a new document when nothing matches. Use to modify existing records in bulk. Both filter and update are required. Not idempotent in general: operators like $inc change state on each call and upsert can insert, though a pure $set repeated on the same matches yields the same end state.', idempotent: false },props: {- database: mongodbCommon.database,- collection: mongodbCommon.collection(),+ database: mongodbProps.database({ required: false }),+ collection: mongodbProps.collection({ required: true }),filter: Property.Json({displayName: 'Filter',description: 'MongoDB query to select documents to update (e.g., {"status": "pending"})',@@ -33,7 +34,7 @@ export default createAction({}),},async run(context) {- const client = await mongodbConnect(context.auth);+ const client = await mongodbClient.create({ auth: context.auth });try {if (!context.propsValue.collection) {diff --git a/packages/pieces/community/mongodb/src/lib/auth.ts b/packages/pieces/community/mongodb/src/lib/auth.tsnew file mode 100644index 00000000000..83d346cadf5--- /dev/null+++ b/packages/pieces/community/mongodb/src/lib/auth.ts@@ -0,0 +1,82 @@+import {+ AppConnectionType,+ PieceAuth,+ Property,+ tryCatch,+} from '@activepieces/pieces-framework';+import { propsValidation } from '@activepieces/pieces-common';+import * as z from 'zod/mini';+import { mongodbClient } from './common/client';+import type { MongodbAuthValue } from './common/types';++export const mongodbAuth = PieceAuth.CustomAuth({+ validate: async ({ auth }) => {+ const { error } = await tryCatch(() => validateAuth({ props: auth }));+ if (error) {+ return {+ valid: false,+ error: error?.message,+ };+ }+ return {+ valid: true,+ };+ },+ props: {+ host: Property.ShortText({+ displayName: 'Host',+ required: true,+ description:+ 'The hostname or address of the MongoDB server (e.g., localhost:27017 or cluster.example.mongodb.net)',+ }),+ useAtlasUrl: Property.Checkbox({+ displayName: 'Use MongoDB Atlas URL Format',+ description:+ 'Enable this if connecting to MongoDB Atlas (uses mongodb+srv:// protocol)',+ required: true,+ defaultValue: false,+ }),+ database: Property.ShortText({+ displayName: 'Database',+ required: false,+ description:+ 'The MongoDB database to connect to (can be specified per action if left empty)',+ }),+ username: Property.ShortText({+ displayName: 'Username',+ required: true,+ description: 'The username to use for connecting to the MongoDB server',+ }),+ password: PieceAuth.SecretText({+ displayName: 'Password',+ description: 'The password to use to identify at the MongoDB server',+ required: true,+ }),+ authSource: Property.ShortText({+ displayName: 'Auth Source',+ required: false,+ description: 'The database to authenticate against (default: admin)',+ defaultValue: 'admin',+ }),+ },+ required: true,+});++async function validateAuth({ props }: { props: MongodbAuthValue['props'] }): Promise<void> {+ await propsValidation.validateZod(props, {+ host: z.string().check(z.minLength(1)),+ useAtlasUrl: z.boolean(),+ database: z.optional(z.string()),+ username: z.string().check(z.minLength(1)),+ password: z.optional(z.string()),+ authSource: z.optional(z.string()),+ });++ const client = await mongodbClient.create({+ auth: { type: AppConnectionType.CUSTOM_AUTH, props },+ });++ await client.db('admin').command({ ping: 1 });++ await client.close();+}diff --git a/packages/pieces/community/mongodb/src/lib/common/ai-props.ts b/packages/pieces/community/mongodb/src/lib/common/ai-props.tsnew file mode 100644index 00000000000..edfb1a85ff4--- /dev/null+++ b/packages/pieces/community/mongodb/src/lib/common/ai-props.ts@@ -0,0 +1,73 @@+import { Property } from '@activepieces/pieces-framework';+import type { PropParams } from './props';++function database<R extends boolean>({+ required,+ displayName = 'Database',+ description = 'Database name. Defaults to the database in the connection. Use List Databases to find it.',+}: PropParams<R>) {+ return Property.ShortText({ displayName, description, required });+}++function collection<R extends boolean>({+ required,+ displayName = 'Collection',+ description = 'Collection name, e.g. "users". Use List Collections to find it.',+}: PropParams<R>) {+ return Property.ShortText({ displayName, description, required });+}++function filter<R extends boolean>({+ required,+ displayName = 'Filter',+ description = `MongoDB query object, e.g. {"status": "active"}. ${EXTENDED_JSON_HINT}`,+}: PropParams<R>) {+ return Property.Json({ displayName, description, required });+}++function update<R extends boolean>({+ required,+ displayName = 'Update',+ description = `MongoDB update operators, e.g. {"$set": {"status": "done"}, "$inc": {"views": 1}}. ${EXTENDED_JSON_HINT}`,+}: PropParams<R>) {+ return Property.Json({ displayName, description, required });+}++function upsert<R extends boolean>({+ required,+ displayName = 'Upsert',+ description = 'Insert a new document when nothing matches the filter. Defaults to false.',+}: PropParams<R>) {+ return Property.StaticDropdown({+ displayName,+ description,+ required,+ options: { options: BOOLEAN_OPTIONS },+ });+}++function projection<R extends boolean>({+ required,+ displayName = 'Projection',+ description = 'Fields to include or exclude, e.g. {"name": 1, "_id": 0}. Omit to return every field.',+}: PropParams<R>) {+ return Property.Json({ displayName, description, required });+}++function limit<R extends boolean>({+ required,+ displayName = 'Limit',+ description = 'Maximum number of results to return (1-1000). Defaults to 100.',+}: PropParams<R>) {+ return Property.Number({ displayName, description, required });+}++export const mongodbAiProps = { database, collection, filter, update, upsert, projection, limit };++const EXTENDED_JSON_HINT =+ 'Use MongoDB Extended JSON for special types: {"$oid": "<24-hex id>"} for an ObjectId, {"$date": "<ISO date>"} for a date.';++const BOOLEAN_OPTIONS = [+ { label: 'True', value: 'true' },+ { label: 'False', value: 'false' },+];diff --git a/packages/pieces/community/mongodb/src/lib/common/api.ts b/packages/pieces/community/mongodb/src/lib/common/api.tsnew file mode 100644index 00000000000..e6763cadf3b--- /dev/null+++ b/packages/pieces/community/mongodb/src/lib/common/api.ts@@ -0,0 +1,61 @@+import type { Collection, Document } from 'mongodb';++async function findAndUpdateDocuments({+ collection,+ filter,+ update,+ upsert,+ returnUpdated,+}: {+ collection: Collection<Document>;+ filter: Document;+ update: Document;+ upsert: boolean;+ returnUpdated: boolean;+}) {+ const updateResult = await collection.updateMany(filter, update, { upsert });++ let documents: Record<string, unknown>[] = [];+ if (returnUpdated) {+ documents = await collection.find(filter).toArray();+ }++ return {+ matchedCount: updateResult.matchedCount,+ modifiedCount: updateResult.modifiedCount,+ upsertedCount: updateResult.upsertedCount,+ upsertedId: updateResult.upsertedId,+ documents: returnUpdated ? documents : undefined,+ };+}++async function findAndReplaceDocument({+ collection,+ filter,+ replacement,+ upsert,+ returnDocumentPreference,+}: {+ collection: Collection<Document>;+ filter: Document;+ replacement: Document;+ upsert: boolean;+ returnDocumentPreference: string;+}) {+ const result = await collection.findOneAndReplace(filter, replacement, {+ upsert,+ returnDocument: returnDocumentPreference === 'before' ? 'before' : 'after',+ includeResultMetadata: true,+ });++ const matchedCount = result.lastErrorObject?.['updatedExisting'] ? 1 : 0;++ return {+ matchedCount,+ modifiedCount: matchedCount,+ upsertedId: result.lastErrorObject?.['upserted'] ?? null,+ document: result.value,+ };+}++export const mongodbApi = { findAndUpdateDocuments, findAndReplaceDocument };diff --git a/packages/pieces/community/mongodb/src/lib/common/client.ts b/packages/pieces/community/mongodb/src/lib/common/client.tsnew file mode 100644index 00000000000..4947a24fa6d--- /dev/null+++ b/packages/pieces/community/mongodb/src/lib/common/client.ts@@ -0,0 +1,50 @@+import { MongoClient, ServerApiVersion } from 'mongodb';+import type { MongodbAuthValue } from './types';++async function create({ auth }: { auth: MongodbAuthValue }): Promise<MongoClient> {+ try {+ const props = auth.props;+ if (!props.host || !props.username || !props.password) {+ throw new Error('Host, username, and password are required');+ }++ const authSource = props.authSource || 'admin';+ const protocol = props.useAtlasUrl ? 'mongodb+srv://' : 'mongodb://';++ let connectionString = `${protocol}${props.username}:${encodeURIComponent(+ props.password+ )}@${props.host}`;++ if (props.database) {+ connectionString += `/${props.database}`;+ }++ connectionString += `?authSource=${authSource}`;++ const finalConnectionString = props.useAtlasUrl+ ? `${connectionString}&retryWrites=true&w=majority`+ : connectionString;++ const client = new MongoClient(finalConnectionString, {+ connectTimeoutMS: 10000,+ serverSelectionTimeoutMS: 10000,+ serverApi: {+ version: ServerApiVersion.v1,+ strict: true,+ deprecationErrors: true,+ },+ });++ await client.connect();++ await client.db('admin').command({ ping: 1 });++ return client;+ } catch (error) {+ const errorMessage =+ error instanceof Error ? error.message : 'Unknown error';+ throw new Error(`Failed to connect to MongoDB: ${errorMessage}`);+ }+}++export const mongodbClient = { create };diff --git a/packages/pieces/community/mongodb/src/lib/common/index.ts b/packages/pieces/community/mongodb/src/lib/common/index.tsdeleted file mode 100644index 6f52442e844..00000000000--- a/packages/pieces/community/mongodb/src/lib/common/index.ts+++ /dev/null@@ -1,129 +0,0 @@-import { AppConnectionValueForAuthProperty, PiecePropValueSchema, Property } from '@activepieces/pieces-framework';-import { MongoClient, Db, ServerApiVersion } from 'mongodb';-import { mongodbAuth } from '../..';--export async function mongodbConnect(- authWithProps: AppConnectionValueForAuthProperty<typeof mongodbAuth>-): Promise<MongoClient> {- try {- const auth = authWithProps.props;- if (!auth.host || !auth.username || !auth.password) {- throw new Error('Host, username, and password are required');- }-- // Build connection string based on whether it's Atlas or standard MongoDB- const authSource = auth.authSource || 'admin';- const protocol = auth.useAtlasUrl ? 'mongodb+srv://' : 'mongodb://';-- let connectionString = `${protocol}${auth.username}:${encodeURIComponent(- auth.password- )}@${auth.host}`;-- if (auth.database) {- connectionString += `/${auth.database}`;- }-- connectionString += `?authSource=${authSource}`;-- // Add common MongoDB Atlas parameters if using Atlas URL format- const finalConnectionString = auth.useAtlasUrl- ? `${connectionString}&retryWrites=true&w=majority`- : connectionString;-- const client = new MongoClient(finalConnectionString, {- connectTimeoutMS: 10000, // 10 seconds timeout for connection- serverSelectionTimeoutMS: 10000, // 10 seconds timeout for server selection- serverApi: {- version: ServerApiVersion.v1,- strict: true,- deprecationErrors: true,- },- });-- await client.connect();-- // For validation purposes, just ping the server- await client.db('admin').command({ ping: 1 });-- console.log('MongoDB connection successful');- return client;- } catch (error) {- const errorMessage =- error instanceof Error ? error.message : 'Unknown error';- throw new Error(`Failed to connect to MongoDB: ${errorMessage}`);- }-}--export async function getDatabase(- client: MongoClient,- databaseName?: string-): Promise<Db> {- return client.db(databaseName);-}--export async function getCollections(- client: MongoClient,- databaseName: string-): Promise<string[]> {- try {- const db = client.db(databaseName);- const collections = await db.listCollections().toArray();- return collections.map((collection) => collection.name);- } catch (error) {- console.error('Error getting collections:', error);- return [];- }-}--export const mongodbCommon = {- database: Property.ShortText({- displayName: 'Database',- description:- 'The MongoDB database to connect to (from your authentication)',- required: false,- }),- collection: (required = true) =>- Property.Dropdown({- auth: mongodbAuth,- displayName: 'Collection',- required,- refreshers: ['database'],- options: async ({ auth, database }) => {- if (!auth) {- return {- disabled: true,- placeholder: 'Connect to MongoDB first',- options: [],- };- }-- const typedAuth = auth- const databaseName = database as string || typedAuth.props.database;-- if (!databaseName) {- return {- disabled: true,- placeholder: 'Database is required in authentication or action',- options: [],- };- }-- const client = await mongodbConnect(typedAuth);-- try {- const collections = await getCollections(client, databaseName);- return {- disabled: false,- options: collections.map((collection: string) => {- return {- label: collection,- value: collection,- };- }),- };- } finally {- await client.close();- }- },- }),-};diff --git a/packages/pieces/community/mongodb/src/lib/common/props.ts b/packages/pieces/community/mongodb/src/lib/common/props.tsnew file mode 100644index 00000000000..89a3309d2b2--- /dev/null+++ b/packages/pieces/community/mongodb/src/lib/common/props.ts@@ -0,0 +1,83 @@+import { DropdownState, Property } from '@activepieces/pieces-framework';+import type { MongoClient } from 'mongodb';+import { mongodbAuth } from '../auth';+import { mongodbClient } from './client';++function database<R extends boolean>({+ required,+ displayName = 'Database',+ description = 'The MongoDB database to connect to (from your authentication)',+}: PropParams<R>) {+ return Property.ShortText({ displayName, description, required });+}++function collection<R extends boolean>({+ required,+ displayName = 'Collection',+ description,+}: PropParams<R>) {+ return Property.Dropdown({+ auth: mongodbAuth,+ displayName,+ description,+ required,+ refreshers: ['database'],+ options: async ({ auth, database }) => {+ if (!auth) {+ return disabledOptions({ placeholder: 'Connect to MongoDB first' });+ }++ const databaseName =+ (typeof database === 'string' && database) || auth.props.database;++ if (!databaseName) {+ return disabledOptions({+ placeholder: 'Database is required in authentication or action',+ });+ }++ const client = await mongodbClient.create({ auth });++ try {+ const collections = await listCollectionNames({ client, databaseName });+ return {+ disabled: false,+ options: collections.map((collection) => ({+ label: collection,+ value: collection,+ })),+ };+ } finally {+ await client.close();+ }+ },+ });+}++async function listCollectionNames({+ client,+ databaseName,+}: {+ client: MongoClient;+ databaseName: string;+}): Promise<string[]> {+ try {+ const db = client.db(databaseName);+ const collections = await db.listCollections().toArray();+ return collections.map((collection) => collection.name);+ } catch {+ return [];+ }+}++function disabledOptions({ placeholder }: { placeholder: string }): DropdownState<never> {+ return { disabled: true, options: [], placeholder };+}++export const mongodbProps = { database, collection };++export type PropParams<R extends boolean> = {+ required: R;+ displayName?: string;+ description?: string;+};diff --git a/packages/pieces/community/mongodb/src/lib/common/types.ts b/packages/pieces/community/mongodb/src/lib/common/types.tsnew file mode 100644index 00000000000..14029f62f90--- /dev/null+++ b/packages/pieces/community/mongodb/src/lib/common/types.ts@@ -0,0 +1,13 @@+import type { AppConnectionType } from '@activepieces/pieces-framework';++export type MongodbAuthValue = {+ type: AppConnectionType.CUSTOM_AUTH;+ props: {+ host: string;+ useAtlasUrl: boolean;+ database?: string;+ username: string;+ password: string;+ authSource?: string;+ };+};diff --git a/packages/pieces/community/mongodb/src/lib/common/utils.ts b/packages/pieces/community/mongodb/src/lib/common/utils.tsnew file mode 100644index 00000000000..9b6941af9a6--- /dev/null+++ b/packages/pieces/community/mongodb/src/lib/common/utils.ts@@ -0,0 +1,18 @@+import type { MongodbAuthValue } from './types';++function databaseName({ auth, database }: { auth: MongodbAuthValue; database?: string }): string {+ const name = database || auth.props.database;+ if (!name) {+ throw new Error('Database is required. Please specify it in the connection settings or in this action.');+ }+ return name;+}++function limit({ value }: { value?: number }): number {+ return Math.min(Math.max(value ?? DEFAULT_LIMIT, 1), MAX_LIMIT);+}++export const mongodbUtils = { databaseName, limit };++const DEFAULT_LIMIT = 100;+const MAX_LIMIT = 1000;diff --git a/packages/pieces/community/mongodb/src/lib/output-schemas.ts b/packages/pieces/community/mongodb/src/lib/output-schemas.tsindex b6028333aaa..43a458824bc 100644--- a/packages/pieces/community/mongodb/src/lib/output-schemas.ts+++ b/packages/pieces/community/mongodb/src/lib/output-schemas.ts@@ -93,3 +93,150 @@ export const findAndReplaceDocumentsOutputSchema: OutputSchema = {},],};++const dropResultFields: OutputSchema['fields'] = [+ { key: 'nIndexesWas', label: 'Indexes Before Drop', format: 'number' },+ { key: 'ok', label: 'OK', format: 'number', description: '1 when the command succeeded.' },+];++export const mongodbBulkWriteOutputSchema: OutputSchema = {+ fields: [+ { key: 'insertedCount', label: 'Inserted Count', format: 'number' },+ { key: 'matchedCount', label: 'Matched Count', format: 'number' },+ { key: 'modifiedCount', label: 'Modified Count', format: 'number' },+ { key: 'deletedCount', label: 'Deleted Count', format: 'number' },+ { key: 'upsertedCount', label: 'Upserted Count', format: 'number' },+ {+ key: 'insertedIds',+ label: 'Inserted IDs',+ dynamicKey: true,+ description: 'Map of operation index to the _id of the inserted document.',+ },+ {+ key: 'upsertedIds',+ label: 'Upserted IDs',+ dynamicKey: true,+ description: 'Map of operation index to the _id of the upserted document.',+ },+ ],+};++export const mongodbCountDocumentsOutputSchema: OutputSchema = {+ fields: [{ key: 'count', label: 'Count', format: 'number' }],+};++export const mongodbCreateCollectionOutputSchema: OutputSchema = {+ fields: [+ { key: 'ok', label: 'OK', format: 'number', description: '1 when the command succeeded.' },+ { key: 'database', label: 'Database' },+ { key: 'collection', label: 'Collection' },+ ],+};++export const mongodbCreateIndexOutputSchema: OutputSchema = {+ fields: [{ key: 'indexName', label: 'Index Name' }],+};++export const mongodbDistinctValuesOutputSchema: OutputSchema = {+ fields: [+ { key: 'values', label: 'Values', description: 'Unique values of the field, sorted ascending.' },+ { key: 'count', label: 'Count', format: 'number' },+ ],+};++export const mongodbDropCollectionOutputSchema: OutputSchema = {+ fields: [+ ...dropResultFields,+ { key: 'ns', label: 'Namespace', description: 'The dropped collection as <database>.<collection>.' },+ { key: 'database', label: 'Database' },+ { key: 'collection', label: 'Collection' },+ ],+};++export const mongodbDropIndexOutputSchema: OutputSchema = {+ fields: dropResultFields,+};++export const mongodbFindOneDocumentOutputSchema: OutputSchema = {+ fields: [+ { key: 'found', label: 'Found', format: 'boolean' },+ {+ key: 'document',+ label: 'Document',+ description: 'The matching document; its fields depend on the collection. Null when nothing matches.',+ },+ ],+};++export const mongodbListCollectionsOutputSchema: OutputSchema = {+ fields: [+ {+ key: 'collections',+ label: 'Collections',+ labelKey: 'name',+ listItems: [+ { key: 'name', label: 'Name' },+ { key: 'type', label: 'Type', description: 'collection, view or timeseries.' },+ { key: 'options', label: 'Options' },+ {+ key: 'info',+ label: 'Info',+ children: [+ { key: 'readOnly', label: 'Read Only', format: 'boolean' },+ { key: 'uuid', label: 'UUID' },+ ],+ },+ {+ key: 'idIndex',+ label: 'ID Index',+ children: [+ { key: 'v', label: 'Index Version', format: 'number' },+ { key: 'key', label: 'Keys', dynamicKey: true },+ { key: 'name', label: 'Name' },+ ],+ },+ ],+ },+ { key: 'count', label: 'Count', format: 'number' },+ ],+};++export const mongodbListDatabasesOutputSchema: OutputSchema = {+ fields: [+ {+ key: 'databases',+ label: 'Databases',+ labelKey: 'name',+ listItems: [+ { key: 'name', label: 'Name' },+ { key: 'sizeOnDisk', label: 'Size on Disk', format: 'filesize' },+ { key: 'empty', label: 'Empty', format: 'boolean' },+ ],+ },+ { key: 'totalSize', label: 'Total Size', format: 'filesize' },+ { key: 'totalSizeMb', label: 'Total Size (MB)', format: 'number' },+ { key: 'ok', label: 'OK', format: 'number', description: '1 when the command succeeded.' },+ ],+};++export const mongodbListIndexesOutputSchema: OutputSchema = {+ fields: [+ {+ key: 'indexes',+ label: 'Indexes',+ labelKey: 'name',+ listItems: [+ { key: 'v', label: 'Index Version', format: 'number' },+ {+ key: 'key',+ label: 'Keys',+ dynamicKey: true,+ description: 'Map of field name to direction (1, -1) or index type such as "text".',+ },+ { key: 'name', label: 'Name' },+ { key: 'unique', label: 'Unique', format: 'boolean' },+ ],+ },+ { key: 'count', label: 'Count', format: 'number' },+ ],+};