如何向BSON对象追加数据?

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

How to append to bson object

问题

我有一个端点,用户可以使用查询参数来过滤Mongo集合。如果只有一个查询参数,比如 title,可以这样做:

filter := bson.M{}

if params.Title != "" {
    filter = bson.M{"title": params.Title}
}

然而,如果有多个查询参数,我似乎无法弄清楚如何追加到 bson 对象中。

我尝试了这样的代码:

filter := []bson.M{}

if params.Title != "" {
    filter = append(filter, bson.M{"title": params.Title})
}

if params.Description != "" {
    filter = append(filter, bson.M{"description": params.Description})
}

但是我得到了这个错误:cannot transform type []primitive.M to a BSON Document: WriteArray can only write a Array while positioned on a Element or Value but is positioned on a TopLevel

我该如何解决这个问题?

英文:

I have an endpoint where users can filter a mongo collection using query parameters. If I have just one query parameter e.g. title, I can do this -

filter := bson.M{}

if params.Title != "" {
	filter = bson.M{"title": params.Title}
}

However, if I have more than one query parameter, I can't seem to get how to append to the bson object.

I tried this -

filter := []bson.M{}

if params.Title != "" {
	filter = append(filter, bson.M{"title": params.Title})
}

if params.Description != "" {
	filter = append(filter, bson.M{"description": params.Description})
}

but I got this error - cannot transform type []primitive.M to a BSON Document: WriteArray can only write a Array while positioned on a Element or Value but is positioned on a TopLevel

How do I solve this?

答案1

得分: 6

bson.M{}go-mongo-driver 中表示为 map[string]interface{}。因此,如果你需要添加更多的元素,就不能使用 append 方法。只需将该值分配给 map 的键,如下所示:

    filter := bson.M{}
	
	if params.Title != "" {
		//filter = bson.M{"title": params.Title}
		filter["title"] = params.Title
	}

	if params.Description != "" {
		filter["description"] =  params.Description
	}
英文:

bson.M{} is underlined map[string]interface{} in go-mongo-driver. So if you need to add more elemnets, you can not append. Just assign that value to map's key as below.

    filter := bson.M{}
	
	if params.Title != "" {
		//filter = bson.M{"title": params.Title}
		filter["title"] = params.Title
	}

	if params.Description != "" {
		filter["description"] =  params.Description
	}

答案2

得分: 1

考虑一个名为test的集合,其中包含一个文档:{ "_id" : 1, "Title" : "t-1", "Description" : "d-1" }

你可以使用以下代码:

title := "t-1"
description := ""    // 或者 "d-1"
filter := bson.M{}

if title != "" {
    filter["Title"] = title
}

if description != "" {
    filter["Description"] = description
}

var result bson.M

collection := client.Database("test").Collection("test")
err := collection.FindOne(context.TODO(), filter).Decode(&result)
if err != nil {
    log.Fatal(err)
}

fmt.Printf("找到一个文档:%+v\n", result)

这段代码用于在test集合中查找满足条件的文档,并将结果存储在result变量中。

英文:

Consider a collection test with a document: { "_id" : 1, "Title" : "t-1", "Description" : "d-1" }
And, you can use the following:

title := "t-1"
description := ""    // or "d-1"
filter := bson.M{}

if Title != "" {
    filter["Title"] = title
}

if Description != "" {
    filter["Description"] = description
}

//fmt.Println(filter);

var result bson.M

collection := client.Database("test").Collection("test")
err := collection.FindOne(context.TODO(), filter).Decode(&result)
if err != nil {
    log.Fatal(err)
}

fmt.Printf("Found a single document: %+v\n", result)

huangapple
  • 本文由 发表于 2021年5月25日 20:53:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/67688353.html
匿名

发表评论

匿名网友

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

确定