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

+106
View File
@@ -24,6 +24,19 @@ pub struct MongoDropIndexesResult {
pub affected_rows: u64,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct MongoCollectionStatsResult {
pub count: serde_json::Value,
pub size: serde_json::Value,
#[serde(rename = "avgObjSize")]
pub avg_obj_size: serde_json::Value,
#[serde(rename = "storageSize")]
pub storage_size: serde_json::Value,
#[serde(rename = "totalIndexSize")]
pub total_index_size: serde_json::Value,
pub nindexes: serde_json::Value,
}
pub async fn connect(url: &str, timeout: Duration, idle_timeout: Duration) -> Result<Client, String> {
let url = normalize_mongo_uri_direct_connection(url);
let is_multi_host = is_multi_host_mongo_uri(&url);
@@ -136,6 +149,52 @@ fn server_version_from_build_info(result: &Document) -> Result<String, String> {
result.get_str("version").map(str::to_string).map_err(|e| format!("MongoDB server version not found: {e}"))
}
pub async fn collection_stats(
client: &Client,
database: &str,
collection: &str,
scale: Option<serde_json::Number>,
) -> Result<MongoCollectionStatsResult, String> {
let database = database.trim();
let collection = collection.trim();
if database.is_empty() {
return Err("Database name is required".to_string());
}
if collection.is_empty() {
return Err("Collection name is required".to_string());
}
let result = client
.database(database)
.run_command(collection_stats_command_document(collection, scale.as_ref()))
.await
.map_err(|e| e.to_string())?;
Ok(collection_stats_result_from_document(&result))
}
fn collection_stats_command_document(collection: &str, scale: Option<&serde_json::Number>) -> Document {
let mut command = doc! { "collStats": collection };
if let Some(scale) = scale {
command.insert("scale", json_value_to_bson(&serde_json::Value::Number(scale.clone())));
}
command
}
fn collection_stats_result_from_document(result: &Document) -> MongoCollectionStatsResult {
MongoCollectionStatsResult {
count: collection_stats_field(result, "count"),
size: collection_stats_field(result, "size"),
avg_obj_size: collection_stats_field(result, "avgObjSize"),
storage_size: collection_stats_field(result, "storageSize"),
total_index_size: collection_stats_field(result, "totalIndexSize"),
nindexes: collection_stats_field(result, "nindexes"),
}
}
fn collection_stats_field(result: &Document, key: &str) -> serde_json::Value {
result.get(key).map(bson_to_json).unwrap_or(serde_json::Value::Null)
}
pub async fn list_databases(client: &Client) -> Result<Vec<String>, String> {
client.list_database_names().await.map_err(|e| e.to_string())
}
@@ -1550,6 +1609,53 @@ mod tests {
assert!(error.contains("MongoDB server version not found"));
}
#[test]
fn collection_stats_result_reads_expected_fields() {
let result = collection_stats_result_from_document(&doc! {
"count": 12_i64,
"size": 4096_i64,
"avgObjSize": 341.3_f64,
"storageSize": 8192_i64,
"totalIndexSize": 2048_i64,
"nindexes": 3_i32,
});
assert_eq!(
result,
MongoCollectionStatsResult {
count: serde_json::json!(12),
size: serde_json::json!(4096),
avg_obj_size: serde_json::json!(341.3),
storage_size: serde_json::json!(8192),
total_index_size: serde_json::json!(2048),
nindexes: serde_json::json!(3),
}
);
}
#[test]
fn collection_stats_result_fills_missing_fields_with_null() {
let result = collection_stats_result_from_document(&doc! {
"count": 7_i32,
"storageSize": 512_i32,
});
assert_eq!(result.count, serde_json::json!(7));
assert_eq!(result.size, serde_json::Value::Null);
assert_eq!(result.avg_obj_size, serde_json::Value::Null);
assert_eq!(result.storage_size, serde_json::json!(512));
assert_eq!(result.total_index_size, serde_json::Value::Null);
assert_eq!(result.nindexes, serde_json::Value::Null);
}
#[test]
fn collection_stats_command_serializes_scale() {
let command = collection_stats_command_document("users", Some(&serde_json::Number::from(1024)));
assert_eq!(command.get_str("collStats").unwrap(), "users");
assert!(matches!(command.get("scale"), Some(Bson::Int64(1024))));
}
#[test]
fn json_object_to_document_parses_mongo_shell_isodate_strings() {
let value = serde_json::json!({
+17 -1
View File
@@ -1,5 +1,5 @@
use crate::connection::{AppState, PoolKind};
use crate::db::mongo_driver::{self, MongoDocumentResult, MongoDropIndexesResult};
use crate::db::mongo_driver::{self, MongoCollectionStatsResult, MongoDocumentResult, MongoDropIndexesResult};
use crate::document_ops::CollectionInfo;
async fn ensure_document_pool(state: &AppState, connection_id: &str) -> Result<(), String> {
@@ -70,6 +70,22 @@ pub async fn mongo_server_version_core(
}
}
pub async fn mongo_collection_stats_core(
state: &AppState,
connection_id: &str,
database: &str,
collection: &str,
scale: Option<serde_json::Number>,
) -> Result<MongoCollectionStatsResult, String> {
ensure_document_pool(state, connection_id).await?;
let connections = state.connections.read().await;
match connections.get(connection_id).ok_or("Not found")? {
PoolKind::MongoDb(client) => mongo_driver::collection_stats(client, database, collection, scale).await,
PoolKind::Agent(_) => Err("MongoDB legacy agent does not support collection stats helpers".to_string()),
_ => Err("Not a MongoDB connection".to_string()),
}
}
#[allow(clippy::too_many_arguments)]
pub async fn mongo_find_documents_core(
state: &AppState,