dongyu7074 2017-08-04 11:31
浏览 252

在mgo中查询字符串数组

I have an element that looks like this:

{"Name":"test name","DBType":0,"UserName":"test user","Password":"","Host":"test host","Port":"123","DBName":"test schema","Options":"test options","Groups":["test1"]}

I want to be able to query the cataloug of Datasources for those which are assigned to a particular group.

My code for this is:

var d []Source
q := bson.M{"Groups": bson.M{"$in": [1]string{groupName}}}
findErr := c.Find(q).All(&d)

However - I get no error and no results.

I've also tried

q := bson.M{"Groups": groupName}

with the same result.

//Source describes a data source
type Source struct {
    Name string
    DBType      uint
    UserName    string
    Password    string
    Host        string
    Port        string
    DBName      string
    Options     string
    Groups      []string
}

I'm stuck - I am puzzled! Any help appreciated.

Update - I tried

{"Name":"test name"}

and this returns 0 items. Yet if I set to nil I get stuff.

  • 写回答

1条回答 默认 最新

  • dongque20030402 2017-08-08 01:16
    关注

    Make sure to double check the capitalisation of your document field names. For example, if in your documents you have

    { "Groups": ["test1", "test2"] }
    

    You also need to query using capital G as below:

    query := bson.M{"Groups": groupName}
    

    I think the issue here is that you have lower case groups in your document.

    Your mgo Struct however is capital Groups, which mgo will automatically map to lower case groups document field. Thus querying using lower case groups field name will not return any match (but query all does). If this is the case, you need to query using:

    query := bson.M{"groups": groupName}
    

    If however, your document field names are in first letter capital, then you also need to specify marshalling mapping as below:

    type Source struct {
        Name     string   `bson:"Name"`
        DBType   uint     `bson:"DBType"`
        UserName string   `bson:"UserName"`
        Password string   `bson:"Password"`
        Host     string   `bson:"Host"`
        Port     string   `bson:"Port"`
        DBName   string   `bson:"DBName"`
        Options  string   `bson:"Options"`
        Groups   []string `bson:"Groups"`
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 用三极管设计—个共射极放大电路
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示