从Golang中的MongoDB获取数据

huangapple go评论86阅读模式
英文:

fetching the data from a mongodb in golang

问题

我正在尝试使用gopkg.in/mgo.v2驱动程序从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'吗?还是我在这里做错了什么。

英文:

I'm trying to fetch data from mongodb in golang using the gopkg.in/mgo.v2 driver, the format of the data is not fixed , as in few rows will be containing some fields which other rows might not.

here is the code for the same

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

Now the data contained in the collection is { "_id" : "3434", "0" : 1 }, however the for loop gives the output as _id , shouldn't there be two keys '_id' and '0' ? or am I doing something wrong here.

答案1

得分: 2

哦,我找到了解决方案。
"result"变量应该是bson.M类型,然后你可以根据需要进行类型转换,以便深入嵌套结构。

英文:

oh I found the solution
the "result" variable should be of type bson.M and then you can typecast accordingly as you go deep into the nesting structure.

答案2

得分: 0

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

不要忘记在下面的代码中重命名您的MongoDB的数据库名称和集合名称。还需要相应更改查询参数。

愉快的编码...

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

// 这是一个用户定义的方法,用于关闭资源。
// 此方法关闭MongoDB连接并取消上下文。
func close(client *mongo.Client, ctx context.Context, cancel context.CancelFunc) {
	defer cancel()
	defer func() {
		if err := client.Disconnect(ctx); err != nil {
			panic(err)
		}
	}()
}

// 这是一个用户定义的方法,返回
// mongo.Client、context.Context、
// context.CancelFunc和错误。
// mongo.Client将用于进一步的数据库
// 操作。context.Context将用于设置
// 进程的截止时间。context.CancelFunc将
// 用于取消上下文和与之关联的资源。
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是用户定义的方法,用于查询MongoDB,
// 接受mongo.client、context、数据库名称、
// 集合名称、查询和字段。

// 数据库名称和集合名称的类型是
// 字符串。查询的类型是接口。
// 字段的类型是接口,用于限制
// 返回的字段。
//
// query方法返回一个游标和错误。
func query(client *mongo.Client, ctx context.Context, dataBase, col string, query, field interface{}) (result *mongo.Cursor, err error) {

	// 选择数据库和集合。
	collection := client.Database(dataBase).Collection(col)

	// 集合有一个Find方法,
	// 根据查询和字段返回一个mongo.cursor。
	result, err = collection.Find(ctx, query,
		options.Find().SetProjection(field))
	return
}

func main() {

	// 从connect方法获取Client、Context、CalcelFunc和err。
	client, ctx, cancel, err := connect("mongodb://localhost:27017")
	if err != nil {
		panic(err)
	}

	// 当main函数返回时释放资源
	defer close(client, ctx, cancel)

	// 创建一个过滤器和选项,类型为接口,
	// 用于存储BSON对象。
	var filter, option interface{}

	// 过滤器获取所有文档,
	// 其中maths字段大于70
	filter = bson.D{
		{"_id", bson.D{{"$eq", 3434}}},
	}

	// 选项从所有文档中删除id字段
	option = bson.D{{"_id", 0}}

	// 使用client、context、数据库名称、集合名称、过滤器和选项调用query方法
	// 此方法返回mongo.cursor和任何错误。
	cursor, err := query(client, ctx, "YourDataBaseName",
		"YourCollectioName", filter, option)
	// 处理错误。
	if err != nil {
		panic(err)
	}

	var results []bson.D

	// 从游标获取BSON对象,
	// 如果有错误则返回错误。
	if err := cursor.All(ctx, &results); err != nil {

		// 处理错误
		panic(err)
	}

	// 打印查询结果。
	fmt.Println("Query Reult")
	for _, doc := range results {
		fmt.Println(doc)
	}
}

希望对您有所帮助!

英文:

Give a try with the following piece of code. This will help you fetching matching records from the Database using BSON Object.

Do not forget to rename the Database name and Collection name of your MongoDB in the below code. Also needs to change the query parameter accordingly.

Happy Coding...

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

huangapple
  • 本文由 发表于 2015年12月20日 23:58:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/34382838.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定