2019-01-20 11:32
浏览 399

如何使用mongo-go-driver 0.2.0在bson.A中使用切片的元素

How do I use a given slice to generate a bson.A? I need this to make dynamic queries.

I am upgrading from mongo-go-driver alpha to beta 0.2.0, and this has become a major change in my project since the API is different now.

input := []string{"bar", "world"}
//expected output
bson.A{"bar", "world"}

图片转代码服务由CSDN问答提供 功能建议

如何使用给定的切片生成bson.A? 我需要用它来进行动态查询。

我正在从mongo-go-driver alpha升级到beta 0.2.0,由于API不同,这已成为我项目中的重大更改。 现在。

https:/ /

  input:= [] string {“ bar”,“ world”  } 
bson.A {“ bar”,“ world”} 
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dsg41888 2019-01-23 22:54

    So bson.A underlying type is []interface{},

    I could just use append to it like a slice

    点赞 打赏 评论
  • douhuang1852 2019-07-26 20:41

    Not sure if you ever found your answer, but I battled with this for an hour+ yesterday.

    I'm not positive this will solve what you're asking. I assume you're trying to build a filter from your input. Ultimately I did not use a bson.A when I was trying to pass an array.

    Situation: Trying to build a filter and one of the bson.D elements is an array.

    I thought I needed to use bson.A.

    My initial assumption:

    return bson.D{
      {"uuid", request.Uuid},
      {"action", request.Action},
      {"resource", bson.D{{"$in", bson.A{resourceStrings}}}},

    where resourceStrings is a slice of strings.

    However this will ultimately build a filter that looks like FILTER : [ {resource [{$in [[Orgs::Organizations::1 Orgs::Organizations::* Orgs::Organizations Orgs::*]]}]}]

    *Note that the $in method is looking for an array of arrays here.

    What we want is: FILTER : [{uuid 80} {action UpdateOrganization} {resource [{$in [Orgs::Organizations::1 Orgs::Organizations::* Orgs::Organizations Orgs::*]}]}]

    If we pass in a literal array of strings it will work...

    return bson.D{
      {"uuid", request.Uuid},
      {"action", request.Action},
      {"resource", bson.D{{"$in", bson.A{"Orgs::Organizations::1", "Orgs::Organizations::*", "Orgs::Organizations", "Orgs::*"}}}},

    After some trial and error I found that bson.D will directly accept the array.

    ultimately I solved the issue thus

    return bson.D{
      {"uuid", request.Uuid},
      {"action", request.Action},
      {"resource", bson.D{{"$in", resourceStrings}}},

    Taking your example literally - if you're simply trying to marshal an array to a bson.A try:


    点赞 打赏 评论

相关推荐 更多相似问题