本文介绍了MongoDB在Go中列出具有给定前缀的数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何仅列出具有给定前缀( prefix _ )的数据库?

How can I list databases only with the given prefix (prefix_)?

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

输出:

[管理栏配置本地prefix_bar prefix_foo]

[prefix_bar prefix_foo]

  1. 在我的情况下 foo 可以创建数据库而无需定义新的 struct 吗?
  2. 我的目标是仅对具有前缀的数据库运行查询,所以可能存在比列出数据库更好的解决方案,然后对每个数据库运行查询吗?
  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?

推荐答案

仅通过 name 属性过滤,该属性表示数据库名称.要列出以给定前缀开头的数据库,您可以使用正则表达式为 ^ prefix _ :

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_"}}

listDatabases 命令上列出了其他过滤器选项页:

Other filter options are listed on the listDatabases command page:

  • 名称
  • sizeOnDisk
  • 分片

您可以使用一个空的 bson.M {} 插入一个空文档(当然会添加 _id ).

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

这篇关于MongoDB在Go中列出具有给定前缀的数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 12:21