【问题标题】:fetching the data from a mongodb in golang从 golang 中的 mongodb 获取数据
【发布时间】:2021-06-27 01:19:13
【问题描述】:

我正在尝试使用 gopkg.in/mgo.v2 驱动程序从 golang 中的 mongodb 获取数据,数据的格式不固定,因为在几行中将包含一些其他行可能不包含的字段。

这是相同的代码

session, err := mgo.Dial("mongodb://root:root@localhost:27017/admin")
db := session.DB("test")
fmt.Println(reflect.TypeOf(db))
CheckError(err,"errpor")
result := make(map[string]string)
//query := make(map[string]string)
//query["_id"] = "3434"

err1 := db.C("mycollection").Find(nil).One(&result)
CheckError(err1,"error")
for k := range result {
    fmt.Println(k)
}

现在集合中包含的数据是 { "_id" : "3434", "0" : 1 },但是 for 循环给出的输出为 _id ,不应该有两个键 '_id' 和 '0 ' ?还是我在这里做错了什么。

【问题讨论】:

    标签: mongodb go


    【解决方案1】:

    哦,我找到了解决方案 “结果”变量应该是 bson.M 类型,然后您可以在深入嵌套结构时进行相应的类型转换。

    【讨论】:

      【解决方案2】:

      试试下面的代码。这将帮助您使用 BSON 对象从数据库中获取匹配的记录。

      不要忘记在下面的代码中重命名 MongoDB 的 Database 名称和 Collection 名称。还需要相应地更改查询参数。

      快乐编码...

      package main
      
      import (
          "context"
          "fmt"
          "time"
      
          "go.mongodb.org/mongo-driver/bson"
          "go.mongodb.org/mongo-driver/mongo"
          "go.mongodb.org/mongo-driver/mongo/options"
      )
      
      // This is a user defined method to close resourses.
      // This method closes mongoDB connection and cancel context.
      func close(client *mongo.Client, ctx context.Context, cancel context.CancelFunc) {
          defer cancel()
          defer func() {
              if err := client.Disconnect(ctx); err != nil {
                  panic(err)
              }
          }()
      }
      
      // This is a user defined method that returns
      // a mongo.Client, context.Context,
      // context.CancelFunc and error.
      // mongo.Client will be used for further database
      // operation. context.Context will be used set
      // deadlines for process. context.CancelFunc will
      // be used to cancel context and resourse
      // assositated with it.
      func connect(uri string) (*mongo.Client, context.Context, context.CancelFunc, error) {
          ctx, cancel := context.WithTimeout(context.Background(),
              30*time.Second)
          client, err := mongo.Connect(ctx, options.Client().ApplyURI(uri))
          return client, ctx, cancel, err
      }
      
      // query is user defined method used to query MongoDB,
      // that accepts mongo.client,context, database name,
      // collection name, a query and field.
      
      // datbase name and collection name is of type
      // string. query is of type interface.
      // field is of type interface, which limts
      // the field being returned.
      
      // query method returns a cursor and error.
      func query(client *mongo.Client, ctx context.Context, dataBase, col string, query, field interface{}) (result *mongo.Cursor, err error) {
      
          // select database and collection.
          collection := client.Database(dataBase).Collection(col)
      
          // collection has an method Find,
          // that returns a mongo.cursor
          // based on query and field.
          result, err = collection.Find(ctx, query,
              options.Find().SetProjection(field))
          return
      }
      
      func main() {
      
          // Get Client, Context, CalcelFunc and err from connect method.
          client, ctx, cancel, err := connect("mongodb://localhost:27017")
          if err != nil {
              panic(err)
          }
      
          // Free the resource when mainn dunction is returned
          defer close(client, ctx, cancel)
      
          // create a filter an option of type interface,
          // that stores bjson objects.
          var filter, option interface{}
      
          // filter gets all document,
          // with maths field greater that 70
          filter = bson.D{
              {"_id", bson.D{{"$eq", 3434}}},
          }
      
          // option remove id field from all documents
          option = bson.D{{"_id", 0}}
      
          // call the query method with client, context,
          // database name, collection name, filter and option
          // This method returns momngo.cursor and error if any.
          cursor, err := query(client, ctx, "YourDataBaseName",
              "YourCollectioName", filter, option)
          // handle the errors.
          if err != nil {
              panic(err)
          }
      
          var results []bson.D
      
          // to get bson object from cursor,
          // returns error if any.
          if err := cursor.All(ctx, &results); err != nil {
      
              // handle the error
              panic(err)
          }
      
          // printing the result of query.
          fmt.Println("Query Reult")
          for _, doc := range results {
              fmt.Println(doc)
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-08-14
        • 1970-01-01
        • 1970-01-01
        • 2016-11-02
        • 2019-06-04
        • 1970-01-01
        相关资源
        最近更新 更多