mongo

package
v0.2.14 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 28, 2026 License: MIT Imports: 9 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type CollectionInfo

type CollectionInfo struct {
	Name           string         `json:"name"`
	Database       string         `json:"database"`
	Type           string         `json:"type"` // "collection" or "view"
	DocCount       int64          `json:"docCount"`
	Size           int64          `json:"size"`           // uncompressed data size in bytes
	AvgObjSize     int64          `json:"avgObjSize"`     // average document size in bytes
	StorageSize    int64          `json:"storageSize"`    // allocated storage in bytes
	TotalIndexSize int64          `json:"totalIndexSize"` // total size of all indexes in bytes
	Indexes        []IndexInfo    `json:"indexes"`
	Validator      *ValidatorInfo `json:"validator,omitempty"`
}

CollectionInfo describes a MongoDB collection with stats.

type Config

type Config struct {
	URI      string
	Database string // empty = all non-system databases
}

Config holds MongoDB connection settings.

type DatabaseInfo

type DatabaseInfo struct {
	Name       string `json:"name"`
	SizeOnDisk int64  `json:"sizeOnDisk"`
	Empty      bool   `json:"empty"`
}

DatabaseInfo describes a MongoDB database.

type FieldFrequency added in v0.2.8

type FieldFrequency struct {
	Path  string           `json:"path"`
	Count int64            `json:"count"`
	Types map[string]int64 `json:"types"`
}

FieldFrequency tracks how often a field path appears and its BSON types.

type FieldSampleResult added in v0.2.8

type FieldSampleResult struct {
	Database      string           `json:"database"`
	Collection    string           `json:"collection"`
	SampleSize    int64            `json:"sampleSize"`
	Fields        []FieldFrequency `json:"fields"`
	MaxDocSize    int64            `json:"maxDocSize,omitempty"`    // largest serialized doc in bytes
	MaxFieldCount int              `json:"maxFieldCount,omitempty"` // most top-level fields in any doc
	ArrayLengths  map[string]int64 `json:"arrayLengths,omitempty"`  // field path → max observed array length
}

FieldSampleResult holds sampled field frequency data for one collection.

type IndexInfo

type IndexInfo struct {
	Name   string      `json:"name"`
	Key    []KeyField  `json:"key"`
	Unique bool        `json:"unique,omitempty"`
	Sparse bool        `json:"sparse,omitempty"`
	TTL    *int32      `json:"ttl,omitempty"`  // TTL seconds, nil if not a TTL index
	Size   int64       `json:"size,omitempty"` // index size in bytes from collStats.indexSizes
	Stats  *IndexStats `json:"stats,omitempty"`
}

IndexInfo describes a single index on a collection.

type IndexStats

type IndexStats struct {
	Ops   int64     `json:"ops"`   // number of operations that used this index
	Since time.Time `json:"since"` // when stats tracking started
}

IndexStats holds usage statistics for an index.

type Inspector

type Inspector struct {
	// contains filtered or unexported fields
}

Inspector reads MongoDB metadata and statistics.

func NewInspector

func NewInspector(ctx context.Context, cfg Config) (*Inspector, error)

NewInspector connects to MongoDB and verifies the connection. The context deadline is used to bound connection and server selection time.

func (*Inspector) Close

func (i *Inspector) Close(ctx context.Context) error

Close disconnects from MongoDB.

func (*Inspector) GetCollectionStats

func (i *Inspector) GetCollectionStats(ctx context.Context, dbName, collName string) (CollectionInfo, map[string]int64, error)

GetCollectionStats populates size/count stats for a collection. Returns the collection info and a map of index name → size in bytes.

func (*Inspector) GetIndexStats

func (i *Inspector) GetIndexStats(ctx context.Context, dbName, collName string) (map[string]IndexStats, error)

GetIndexStats returns usage statistics for all indexes on a collection.

func (*Inspector) GetIndexes

func (i *Inspector) GetIndexes(ctx context.Context, dbName, collName string) ([]IndexInfo, error)

GetIndexes returns index definitions for a collection.

func (*Inspector) GetServerVersion

func (i *Inspector) GetServerVersion(ctx context.Context) (ServerInfo, error)

GetServerVersion returns the MongoDB server version string.

func (*Inspector) GetValidators added in v0.2.1

func (i *Inspector) GetValidators(ctx context.Context, database string) ([]ValidatorInfo, error)

GetValidators returns JSON schema validators configured on collections.

func (*Inspector) Inspect

func (i *Inspector) Inspect(ctx context.Context, database string) ([]CollectionInfo, error)

Inspect gathers full metadata for all collections in the given databases.

func (*Inspector) InspectReplicaSet added in v0.2.13

func (i *Inspector) InspectReplicaSet(ctx context.Context) (ReplicaSetInfo, error)

InspectReplicaSet queries replSetGetStatus, replSetGetConfig, and oplog metadata to build a ReplicaSetInfo. Returns empty info for standalone deployments. Returns partial results on permission errors.

func (*Inspector) InspectSecurity added in v0.2.10

func (i *Inspector) InspectSecurity(ctx context.Context) (SecurityInfo, error)

bsonRawToKeyFields converts a bson.Raw key document to ordered []KeyField. Handles numeric directions (1, -1) and string index types ("text", "2dsphere", InspectSecurity queries server parameters and command-line options to assess security configuration. Requires admin access. Returns partial results on permission errors rather than failing completely.

func (*Inspector) InspectSharding added in v0.2.1

func (i *Inspector) InspectSharding(ctx context.Context) (ShardingInfo, error)

InspectSharding gathers sharding metadata from config collections. Returns Enabled=false with no error for non-sharded deployments.

func (*Inspector) InspectUsers added in v0.2.0

func (i *Inspector) InspectUsers(ctx context.Context, dbName string) ([]UserInfo, error)

InspectUsers queries the usersInfo command on a database and returns user metadata.

func (*Inspector) ListCollections

func (i *Inspector) ListCollections(ctx context.Context, dbName string) ([]CollectionInfo, error)

ListCollections returns metadata for all collections in a database.

func (*Inspector) ListDatabases

func (i *Inspector) ListDatabases(ctx context.Context, database string) ([]DatabaseInfo, error)

ListDatabases returns non-system databases, or a single database if cfg.Database is set.

func (*Inspector) ReadProfiler added in v0.2.1

func (i *Inspector) ReadProfiler(ctx context.Context, database string, limit int64) ([]ProfileEntry, error)

ReadProfiler reads recent profiler entries from system.profile and normalizes query shapes. It never modifies profiler settings and returns an empty slice when profiler data is unavailable.

func (*Inspector) SampleDocuments added in v0.2.8

func (i *Inspector) SampleDocuments(ctx context.Context, database string, sampleSize int64) ([]FieldSampleResult, error)

SampleDocuments samples documents from each collection and builds field frequency maps. Uses $sample aggregation to randomly select documents, then flattens them into dot-notation field paths with BSON type counts. Skips views and system collections.

type KeyField

type KeyField struct {
	Field     string `json:"field"`
	Direction int    `json:"direction"` // 1 (asc) or -1 (desc)
}

KeyField is an ordered index key element.

type ProfileEntry added in v0.2.1

type ProfileEntry struct {
	Database         string    `json:"database"`
	Collection       string    `json:"collection"`
	FilterFields     []string  `json:"filterFields,omitempty"`
	SortFields       []string  `json:"sortFields,omitempty"`
	ProjectionFields []string  `json:"projectionFields,omitempty"`
	DurationMillis   int64     `json:"durationMillis"`
	Timestamp        time.Time `json:"timestamp"`
	PlanSummary      string    `json:"planSummary,omitempty"`
}

ProfileEntry represents a normalized slow-query profiler document shape.

type ReplicaSetInfo added in v0.2.13

type ReplicaSetInfo struct {
	Name             string             `json:"name"`
	Members          []ReplicaSetMember `json:"members"`
	OplogSizeMB      int64              `json:"oplogSizeMB"`
	OplogWindowHours float64            `json:"oplogWindowHours"`
}

ReplicaSetInfo holds replica set topology and oplog metadata.

type ReplicaSetMember added in v0.2.13

type ReplicaSetMember struct {
	Name     string  `json:"name"`     // host:port
	StateStr string  `json:"stateStr"` // PRIMARY, SECONDARY, RECOVERING, etc.
	Health   int     `json:"health"`   // 1 = up, 0 = down
	Priority float64 `json:"priority"`
	Hidden   bool    `json:"hidden"`
	Votes    int     `json:"votes"`
}

ReplicaSetMember describes a single member of a replica set.

type SecurityInfo added in v0.2.10

type SecurityInfo struct {
	AuthEnabled          bool   `json:"authEnabled"`
	TLSMode              string `json:"tlsMode"`
	TLSAllowInvalidCerts bool   `json:"tlsAllowInvalidCerts"`
	BindIP               string `json:"bindIp"`
	AuditLogEnabled      bool   `json:"auditLogEnabled"`
	LocalhostAuthBypass  bool   `json:"localhostAuthBypass"`
}

SecurityInfo holds server security configuration for hardening audits.

type ServerInfo

type ServerInfo struct {
	Version string `json:"version"`
}

ServerInfo holds basic server metadata.

type ShardedCollectionInfo added in v0.2.1

type ShardedCollectionInfo struct {
	Namespace         string           `json:"namespace"`
	Database          string           `json:"database"`
	Collection        string           `json:"collection"`
	Key               []KeyField       `json:"key"`
	ChunkCount        int64            `json:"chunkCount"`
	ChunkDistribution map[string]int64 `json:"chunkDistribution,omitempty"`
	JumboChunks       int64            `json:"jumboChunks"`
	ChunkLimitHit     bool             `json:"chunkLimitHit,omitempty"`
}

ShardedCollectionInfo captures shard key and chunk metadata for one collection.

type ShardingInfo added in v0.2.1

type ShardingInfo struct {
	Enabled         bool                    `json:"enabled"`
	BalancerEnabled bool                    `json:"balancerEnabled"`
	Shards          []string                `json:"shards,omitempty"`
	Collections     []ShardedCollectionInfo `json:"collections,omitempty"`
}

ShardingInfo captures cluster-level sharding metadata used for audit checks.

type UserInfo added in v0.2.0

type UserInfo struct {
	Username string     `json:"user" bson:"user"`
	Database string     `json:"db"   bson:"db"`
	Roles    []UserRole `json:"roles" bson:"roles"`
}

UserInfo describes a MongoDB user from db.getUsers().

type UserRole added in v0.2.0

type UserRole struct {
	Role string `json:"role" bson:"role"`
	DB   string `json:"db"   bson:"db"`
}

UserRole describes a single role assigned to a user.

type ValidatorField added in v0.2.1

type ValidatorField struct {
	BSONTypes []string `json:"bsonTypes,omitempty"`
}

ValidatorField captures expected BSON types for a single schema property.

type ValidatorInfo added in v0.2.1

type ValidatorInfo struct {
	Collection       string          `json:"collection"`
	Database         string          `json:"database"`
	Schema           ValidatorSchema `json:"schema"`
	ValidationLevel  string          `json:"validationLevel,omitempty"`
	ValidationAction string          `json:"validationAction,omitempty"`
}

ValidatorInfo describes collection-level JSON Schema validation settings.

type ValidatorSchema added in v0.2.1

type ValidatorSchema struct {
	Required             []string                  `json:"required,omitempty"`
	AdditionalProperties *bool                     `json:"additionalProperties,omitempty"`
	Properties           map[string]ValidatorField `json:"properties,omitempty"`
}

ValidatorSchema is a normalized subset of MongoDB JSON Schema we analyze.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL