Question
How can I list databases only with the given prefix (prefix_
)?
Example:
package main
import (
"context"
"fmt"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"log"
)
type foo struct {
Value string
}
func main() {
clientOptions := options.Client().ApplyURI("mongodb://10.0.12.76:27018")
client, err := mongo.Connect(context.TODO(), clientOptions)
if err != nil {
log.Fatal(err)
}
db := [3]string{"prefix_foo", "prefix_bar", "bar"}
for _, element := range db {
_, err := client.Database(element).Collection("placeholder").InsertOne(context.TODO(), foo{"sth"})
if err != nil {
log.Fatal(err)
}
}
filter := bson.D{{}}
dbs, err := client.ListDatabaseNames(context.TODO(), filter)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v
", dbs)
}
Output:
[admin bar config local prefix_bar prefix_foo]
Expected output:
[prefix_bar prefix_foo]
Bonus:
- It is possible to create a database without defining new
struct
in my casefoo
? - My goal is to run a query on databases only with a prefix, so maybe better solution exists than listing dbs and then run a query on each database?