title: MongoDB list databases with given prefix in Go
body: <h1>Question</h1>
  <p>How can I list databases only with the given prefix (<code>prefix_</code>)?</p>
  <h1>Example:</h1>
  <pre class="lang-golang prettyprint-override"><code>package main
  
  import (
    &quot;context&quot;
    &quot;fmt&quot;
    &quot;go.mongodb.org/mongo-driver/bson&quot;
    &quot;go.mongodb.org/mongo-driver/mongo&quot;
    &quot;go.mongodb.org/mongo-driver/mongo/options&quot;
    &quot;log&quot;
  )
  
  type foo struct {
    Value string
  }
  
  func main() {
    clientOptions := options.Client().ApplyURI(&quot;mongodb://10.0.12.76:27018&quot;)
    client, err := mongo.Connect(context.TODO(), clientOptions)
    if err != nil {
      log.Fatal(err)
    }
    db := [3]string{&quot;prefix_foo&quot;, &quot;prefix_bar&quot;, &quot;bar&quot;}
  
    for _, element := range db {
      _, err := client.Database(element).Collection(&quot;placeholder&quot;).InsertOne(context.TODO(), foo{&quot;sth&quot;})
      if err != nil {
        log.Fatal(err)
      }
    }
  
    filter := bson.D{{}}
  
    dbs, err := client.ListDatabaseNames(context.TODO(), filter)
    if err != nil {
      log.Fatal(err)
    }
    fmt.Printf(&quot;%+v\n&quot;, dbs)
  }
  </code></pre>
  <h1>Output:</h1>
  <p><code>[admin bar config local prefix_bar prefix_foo]</code></p>
  <h1>Expected output:</h1>
  <p><code>[prefix_bar prefix_foo]</code></p>
  <h1>Bonus:</h1>
  <ol>
  <li>It is possible to create a database without defining new <code>struct</code> in my case <code>foo</code>?</li>
  <li>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?</li>
  </ol>