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 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧