feat(mongodb): support collection stats shell commands

Add db.coll.stats() / dataSize() / storageSize(scale) / totalIndexSize()
so these MongoDB shell commands return a result grid instead of the
"Use MongoDB shell-style commands" error (issue #2529).

- backend: collStats via mongo_driver.collection_stats, wired through
  mongo_ops, the dbx-web /mongo/collection-stats route, the tauri
  mongo_collection_stats command, and the MCP data bridge
- node-core: parseMongoCollectionStatsCommand + result formatter and
  executeQuery dispatch (web build + MCP path)
- desktop: mirror the parser/executor/autocomplete in mongoShellCommand.ts,
  queryStore.ts, api/tauri/http facade, and mongoCompletion.ts
- tests for the parser, result formatter, and completion entries

Close #2529
This commit is contained in:
onenewcode authored and GitHub committed 2026-07-03 21:32:29 +08:00
1 parent a0e9acce95
commit 91c77e53c4
18 files changed
+518 -5

No files matched your search

+1
View File
@@ -390,6 +390,7 @@ export const documentFindDocuments = forward("documentFindDocuments");
export const mongoFindDocuments = forward("mongoFindDocuments");
export const mongoServerVersion = forward("mongoServerVersion");
export const mongoAggregateDocuments = forward("mongoAggregateDocuments");
export const mongoCollectionStats = forward("mongoCollectionStats");
export const mongoCreateIndex = forward("mongoCreateIndex");
export const mongoDropIndexes = forward("mongoDropIndexes");
export const documentInsertDocument = forward("documentInsertDocument");
+5
View File
@@ -64,6 +64,7 @@ import type {
KvPutResponse,
KvDeleteResponse,
MongoDocumentResult,
MongoCollectionStatsResult,
MongoGridFsBucketInfo,
HistoryEntry,
SqlFileRequest,
@@ -1859,6 +1860,10 @@ export async function mongoAggregateDocuments(connectionId: string, database: st
return post("/api/mongo/aggregate-documents", { connectionId, database, collection, pipelineJson, maxRows, executionId });
}
export async function mongoCollectionStats(connectionId: string, database: string, collection: string, scale?: number, executionId?: string): Promise<MongoCollectionStatsResult> {
return post("/api/mongo/collection-stats", { connectionId, database, collection, scale, executionId });
}
export async function mongoCreateIndex(connectionId: string, database: string, collection: string, keysJson: string, optionsJson?: string): Promise<{ name: string }> {
return post("/api/mongo/create-index", { connectionId, database, collection, keysJson, optionsJson });
}
+4
View File
@@ -39,6 +39,10 @@ const COLLECTION_METHODS = [
{ label: "deleteOne", detail: "Delete one matching document", apply: "deleteOne({})" },
{ label: "deleteMany", detail: "Delete all matching documents", apply: "deleteMany({})" },
{ label: "getIndexes", detail: "List collection indexes", apply: "getIndexes()" },
{ label: "stats", detail: "Show collection statistics", apply: "stats()" },
{ label: "dataSize", detail: "Total size of documents in bytes", apply: "dataSize()" },
{ label: "storageSize", detail: "Allocated storage size in bytes", apply: "storageSize()" },
{ label: "totalIndexSize", detail: "Total size of all indexes in bytes", apply: "totalIndexSize()" },
{ label: "createIndex", detail: "Create an index", apply: "createIndex({ ${field}: 1 })" },
{ label: "dropIndex", detail: "Drop one index", apply: 'dropIndex("${indexName}")' },
{ label: "dropIndexes", detail: "Drop collection indexes", apply: "dropIndexes()" },
+56
View File
@@ -31,6 +31,14 @@ export interface MongoVersionCommand {
kind: "version";
}
export type MongoCollectionStatsMetric = "stats" | "dataSize" | "storageSize" | "totalIndexSize";
export interface MongoCollectionStatsCommand {
collection: string;
metric: MongoCollectionStatsMetric;
scale?: number;
}
type MongoWriteKind = "insert" | "update" | "delete" | "createIndex" | "dropIndex" | "dropIndexes";
export type MongoCommand =
@@ -39,6 +47,7 @@ export type MongoCommand =
| ({ kind: "countDocuments" } & MongoCountDocumentsCommand)
| ({ kind: "aggregate" } & MongoAggregateCommand)
| ({ kind: "getIndexes" } & MongoGetIndexesCommand)
| ({ kind: "collectionStats" } & MongoCollectionStatsCommand)
| ({ kind: "use" } & MongoUseCommand)
| { kind: "insert"; collection: string; docsJson: string }
| { kind: "update"; collection: string; filter: string; update: string; many: boolean }
@@ -223,6 +232,29 @@ export function parseMongoGetIndexesCommand(input: string): MongoGetIndexesComma
};
}
export function parseMongoCollectionStatsCommand(input: string): MongoCollectionStatsCommand | null {
const source = input.trim().replace(/;$/, "").trim();
for (const metric of ["stats", "dataSize", "storageSize", "totalIndexSize"] as const) {
const target = parseCollectionMethodTarget(source, metric);
if (!target) continue;
const args = parseMethodArgs(source, target.methodCallIndex);
if (!args) return null;
const scale = parseMongoCollectionStatsScale(args);
return scale === null ? null : { collection: target.collection, metric, ...(scale === undefined ? {} : { scale }) };
}
return null;
}
function parseMongoCollectionStatsScale(args: string[]): number | undefined | null {
if (args.length === 1 && !args[0]?.trim()) return undefined;
if (args.length !== 1) return null;
const raw = args[0].trim();
if (!/^[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?$/.test(raw)) return null;
const scale = Number(raw);
if (!Number.isFinite(scale)) return null;
return scale;
}
export function parseMongoUseCommand(input: string): MongoUseCommand | null {
const source = input.trim().replace(/;$/, "").trim();
const match = /^use\s+([a-zA-Z0-9_-]+)$/i.exec(source);
@@ -340,6 +372,10 @@ export function parseMongoCommand(input: string): ParsedMongoCommand | null {
const getIndexes = parseMongoGetIndexesCommand(source);
return getIndexes ? { kind: "getIndexes", ...getIndexes } : null;
},
(source) => {
const stats = parseMongoCollectionStatsCommand(source);
return stats ? { kind: "collectionStats", ...stats } : null;
},
(source) => {
const write = parseMongoWriteCommand(source);
return write ?? null;
@@ -529,6 +565,26 @@ export function mongoIndexesToQueryResult(
};
}
export function mongoCollectionStatsToQueryResult(metric: MongoCollectionStatsMetric, stats: Record<string, unknown>, executionTimeMs: number): QueryResult {
const execution_time_ms = Math.max(0, Math.round(executionTimeMs));
if (metric === "stats") {
const columns = ["count", "size", "avgObjSize", "storageSize", "totalIndexSize", "nindexes"];
return {
columns,
rows: [columns.map((column) => (column in stats ? toCellValue(stats[column]) : null))],
affected_rows: 1,
execution_time_ms,
};
}
const sourceField = metric === "dataSize" ? "size" : metric;
return {
columns: [metric],
rows: [[sourceField in stats ? toCellValue(stats[sourceField]) : null]],
affected_rows: 1,
execution_time_ms,
};
}
function parseFindTarget(source: string): { collection: string; findCallIndex: number } | null {
const direct = parseCollectionMethodTarget(source, "find");
if (direct) {
+13
View File
@@ -1484,6 +1484,15 @@ export interface MongoDocumentResult {
total: number;
}
export interface MongoCollectionStatsResult {
count: unknown;
size: unknown;
avgObjSize: unknown;
storageSize: unknown;
totalIndexSize: unknown;
nindexes: unknown;
}
export interface MongoGridFsFileInfo {
id: string;
filename?: string;
@@ -1595,6 +1604,10 @@ export async function mongoAggregateDocuments(connectionId: string, database: st
return invoke("mongo_aggregate_documents", { connectionId, database, collection, pipelineJson, maxRows, executionId });
}
export async function mongoCollectionStats(connectionId: string, database: string, collection: string, scale?: number, executionId?: string): Promise<MongoCollectionStatsResult> {
return invoke("mongo_collection_stats", { connectionId, database, collection, scale, executionId });
}
export async function mongoCreateIndex(connectionId: string, database: string, collection: string, keysJson: string, optionsJson?: string): Promise<{ name: string }> {
return invoke("mongo_create_index", { connectionId, database, collection, keysJson, optionsJson });
}