Skip to main content
Glama
jonfreeland

MongoDB MCP Server

by jonfreeland

find_by_ids

Retrieve multiple MongoDB documents by their IDs in one request to improve efficiency, preserve order, and optionally filter fields with projection.

Instructions

Find multiple documents by their IDs in a single request.

Advantages:

  • More efficient than multiple single document lookups

  • Preserves ID order in results when possible

  • Can filter specific fields with projection

  • Handles both string and ObjectId identifiers

Example: use_mcp_tool with server_name: "mongodb", tool_name: "find_by_ids", arguments: { "collection": "products", "ids": ["5f8d0f3c", "5f8d0f3d", "5f8d0f3e"], "idField": "_id", "projection": { "name": 1, "price": 1 } }

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
databaseNoDatabase name (optional if default database is configured)
collectionYesCollection name
idsYesArray of document IDs to look up
idFieldNoField containing the IDs (default: "_id")
projectionNoMongoDB projection to specify fields to return (optional)

Implementation Reference

  • Handler for the 'find_by_ids' tool. It extracts parameters, validates inputs, performs a MongoDB find query with $in operator on the specified idField, applies optional projection, retrieves the documents, and returns them as JSON.
    case 'find_by_ids': {
      const { database, collection, ids, idField = '_id', projection } = request.params.arguments as {
        database?: string;
        collection: string;
        ids: (string | number)[];
        idField?: string;
        projection?: object;
      };
      const dbName = database || this.defaultDatabase;
      if (!dbName) {
        throw new McpError(
          ErrorCode.InvalidRequest,
          'Database name is required when no default database is configured'
        );
      }
      
      if (!Array.isArray(ids) || ids.length === 0) {
        throw new McpError(
          ErrorCode.InvalidRequest,
          'The ids parameter must be a non-empty array'
        );
      }
      
      const db = client.db(dbName);
      let query = db.collection(collection).find({ [idField]: { $in: ids } });
      
      if (projection) {
        query = query.project(projection);
      }
      
      const results = await query.toArray();
      
      return {
        content: [
          {
            type: 'text',
            text: JSON.stringify(results, null, 2),
          },
        ],
      };
    }
  • Input schema definition for the 'find_by_ids' tool, specifying parameters like database, collection, ids array, idField, and optional projection with types and requirements.
    inputSchema: {
      type: 'object',
      properties: {
        database: {
          type: 'string',
          description: 'Database name (optional if default database is configured)',
        },
        collection: {
          type: 'string',
          description: 'Collection name',
        },
        ids: {
          type: 'array',
          description: 'Array of document IDs to look up',
          items: {
            type: ['string', 'number'],
          },
        },
        idField: {
          type: 'string',
          description: 'Field containing the IDs (default: "_id")',
        },
        projection: {
          type: 'object',
          description: 'MongoDB projection to specify fields to return (optional)',
        },
      },
      required: ['collection', 'ids'],
    },
  • src/index.ts:794-842 (registration)
    Registration of the 'find_by_ids' tool in the ListToolsRequestSchema handler. Includes the tool name, description, and input schema used by MCP clients to discover and invoke the tool.
              name: 'find_by_ids',
              description: `Find multiple documents by their IDs in a single request.
      
    Advantages:
    - More efficient than multiple single document lookups
    - Preserves ID order in results when possible
    - Can filter specific fields with projection
    - Handles both string and ObjectId identifiers
    
    Example:
    use_mcp_tool with
      server_name: "mongodb",
      tool_name: "find_by_ids",
      arguments: {
        "collection": "products",
        "ids": ["5f8d0f3c", "5f8d0f3d", "5f8d0f3e"],
        "idField": "_id",
        "projection": { "name": 1, "price": 1 }
      }`,
              inputSchema: {
                type: 'object',
                properties: {
                  database: {
                    type: 'string',
                    description: 'Database name (optional if default database is configured)',
                  },
                  collection: {
                    type: 'string',
                    description: 'Collection name',
                  },
                  ids: {
                    type: 'array',
                    description: 'Array of document IDs to look up',
                    items: {
                      type: ['string', 'number'],
                    },
                  },
                  idField: {
                    type: 'string',
                    description: 'Field containing the IDs (default: "_id")',
                  },
                  projection: {
                    type: 'object',
                    description: 'MongoDB projection to specify fields to return (optional)',
                  },
                },
                required: ['collection', 'ids'],
              },
            },
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full burden and does so effectively by disclosing key behavioral traits: it explains efficiency benefits, result ordering ('preserves ID order in results when possible'), input flexibility ('handles both string and ObjectId identifiers'), and optional filtering ('can filter specific fields with projection'). It does not cover error handling or performance limits, but adds substantial value beyond basic function.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is well-structured with a clear purpose statement, bullet-pointed advantages, and a practical example. Every sentence adds value, but it could be more front-loaded by integrating the example more seamlessly. It avoids redundancy and is appropriately sized for the tool's complexity.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given no annotations and no output schema, the description provides good contextual completeness for a read operation: it covers purpose, advantages, and usage example. However, it lacks details on output format (e.g., result structure or error cases), which would be helpful since there's no output schema. It adequately addresses the tool's functionality but has minor gaps.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so the baseline is 3. The description adds minimal parameter semantics beyond the schema, such as implying 'ids' can include mixed types and 'projection' for field filtering, but does not elaborate on syntax or defaults (e.g., 'idField' default is only in schema). It compensates slightly with the example showing parameter usage.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the specific action ('Find multiple documents by their IDs') and resource ('documents'), distinguishing it from siblings like 'query' or 'get_distinct_values' by emphasizing batch ID-based lookup. It explicitly mentions efficiency advantages over single lookups, making the purpose distinct and well-defined.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides clear context for when to use this tool ('more efficient than multiple single document lookups') and implies alternatives by mentioning its batch nature, but does not explicitly name when-not-to-use scenarios or compare to specific siblings like 'query' for non-ID-based searches. The example illustrates typical usage, enhancing practical guidance.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/jonfreeland/mongodb-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server