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"`
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条