| 144 | * Introspect MongoDB to get databases, collections, and indexes |
| 145 | */ |
| 146 | export async function executeIntrospect( |
| 147 | client: MongoClient, |
| 148 | database?: string |
| 149 | ): Promise<{ |
| 150 | message: string |
| 151 | databases: string[] |
| 152 | collections: MongoDBCollectionInfo[] |
| 153 | }> { |
| 154 | const databases: string[] = [] |
| 155 | const collections: MongoDBCollectionInfo[] = [] |
| 156 | |
| 157 | if (database) { |
| 158 | databases.push(database) |
| 159 | const db = client.db(database) |
| 160 | const collectionList = await db.listCollections().toArray() |
| 161 | |
| 162 | for (const collInfo of collectionList) { |
| 163 | const coll = db.collection(collInfo.name) |
| 164 | const indexes = await coll.indexes() |
| 165 | const documentCount = await coll.estimatedDocumentCount() |
| 166 | |
| 167 | collections.push({ |
| 168 | name: collInfo.name, |
| 169 | type: collInfo.type || 'collection', |
| 170 | documentCount, |
| 171 | indexes: indexes.map((idx) => ({ |
| 172 | name: idx.name || '', |
| 173 | key: idx.key as Record<string, number>, |
| 174 | unique: idx.unique || false, |
| 175 | sparse: idx.sparse, |
| 176 | })), |
| 177 | }) |
| 178 | } |
| 179 | } else { |
| 180 | const admin = client.db().admin() |
| 181 | const dbList = await admin.listDatabases() |
| 182 | |
| 183 | for (const dbInfo of dbList.databases) { |
| 184 | databases.push(dbInfo.name) |
| 185 | } |
| 186 | } |
| 187 | |
| 188 | const message = database |
| 189 | ? `Found ${collections.length} collections in database '${database}'` |
| 190 | : `Found ${databases.length} databases` |
| 191 | |
| 192 | return { |
| 193 | message, |
| 194 | databases, |
| 195 | collections, |
| 196 | } |
| 197 | } |