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.
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"`
}