Filter out views and system collections after listing all collections. Some MongoDB Atlas tiers (e.g., free tier) don't support regex filters in ListCollections.
(ctx context.Context, client *mongo.Client, databaseName string)
| 31 | // Filter out views and system collections after listing all collections. |
| 32 | // Some MongoDB Atlas tiers (e.g., free tier) don't support regex filters in ListCollections. |
| 33 | func GetCollectionNames(ctx context.Context, client *mongo.Client, databaseName string) ([]string, error) { |
| 34 | db := client.Database(databaseName) |
| 35 | cur, err := db.ListCollections(ctx, bson.D{}) |
| 36 | if err != nil { |
| 37 | return nil, err |
| 38 | } |
| 39 | defer cur.Close(ctx) |
| 40 | |
| 41 | type CollectionSpec struct { |
| 42 | Name string `bson:"name"` |
| 43 | Type string `bson:"type"` // "collection" | "view" | etc |
| 44 | } |
| 45 | |
| 46 | filteredCollNames := make([]string, 0, 100) |
| 47 | for cur.Next(ctx) { |
| 48 | if err := cur.Err(); err != nil { |
| 49 | return nil, err |
| 50 | } |
| 51 | |
| 52 | var coll CollectionSpec |
| 53 | if err := cur.Decode(&coll); err != nil { |
| 54 | return nil, err |
| 55 | } |
| 56 | |
| 57 | if strings.HasPrefix(coll.Name, "system.") { |
| 58 | continue |
| 59 | } |
| 60 | if strings.EqualFold(coll.Type, "view") { |
| 61 | continue |
| 62 | } |
| 63 | filteredCollNames = append(filteredCollNames, coll.Name) |
| 64 | } |
| 65 | slices.Sort(filteredCollNames) |
| 66 | return filteredCollNames, nil |
| 67 | } |
no test coverage detected