3

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\n", dbs)
}

Output:

[admin bar config local prefix_bar prefix_foo]

Expected output:

[prefix_bar prefix_foo]

Bonus:

  1. It is possible to create a database without defining new struct in my case foo?
  2. 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?
Community
  • 1
  • 1
FL3SH
  • 2,996
  • 1
  • 17
  • 25
  • Try `bson.D{{"name", primitive.Regex{Pattern: "^"+prefix +"*", Options: "i"}}}`, or `bson.D{{"name", bson.D{{"$regex", "^"+prefix+"*"}, {"$options", "i"}}}`. – mkopriva Aug 27 '19 at 13:26

1 Answers1

5

Simply filter by the name property, which denotes the database name. And to list databases starting with a given prefix, you may use a regexp being ^prefix_:

filter := bson.M{"name": primitive.Regex{Pattern: "^prefix_"}}

Other filter options are listed on the listDatabases command page:

You can specify a condition on any of the fields in the output of listDatabases:

  • name
  • sizeOnDisk
  • empty
  • shards

And you may use an empty bson.M{} to insert an empty document (_id will be added of course).

Community
  • 1
  • 1
icza
  • 389,944
  • 63
  • 907
  • 827
  • Thank you, I am pretty sure that I tried sth similar. Anyway, how can I list all property to use it for search? – FL3SH Aug 27 '19 at 13:47