duanke6249 2019-08-27 13:08
浏览 206
已采纳

MongoDB在Go中列出具有给定前缀的数据库

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:

  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?
  • 写回答

1条回答 默认 最新

  • doubo82706 2019-08-27 13:26
    关注

    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).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分