我在mgo中使用管道功能来检索数据。我的数据结构如下。
var companyResults []Company
pipeline := []bson.M{
{"$match": bson.M{"slug": slug}},
{"$unwind": "$companyusers"},
{"$match": bson.M{
"companyusers.username": username,
}},
}
err := c.Pipe(pipeline).All(&companyResults)
我需要检查一个给定的" UserName"在" CompanyUsers"在"公司"给定的" Slug"。
Slug和UserName均由用户提供。
使用管道功能我成功完成了搜索,但返回的数据是空的CompanyUsers数组。
我的查询如下:
[{ObjectIdHex("573aa0fddd731711c94830ca") MyCompany companyslug [] }]
这为我提供了如下搜索结果:
{{1}}
无法检索CompanyUsers中的任何数据。我该如何解决这个错误?
答案 0 :(得分:5)
Try making companyResults
a []map[string]interface{}
instead of a []Company
to see what sort of a result you get. This helps to figure out what the structure of companyResults
should be.
var companyResults []map[string]interface{}
You will see a result like,
[map[companyname:MyCompany slug:companyslug companyusers:map[username:username] _id:test]]
See that companyusers
is infact a map not an array. This is because your usage of the $unwind
stage. It deconstructs the array, outputting one document for each element in the array. See docs.
I agree with John Smith's answer, that you do not need pipelines at all. But following should give you the desired result.
type Result struct {
Id string `bson:"_id,omitempty"`
CompanyName string
Slug string
CompanyUsers CompanyUser
}
var companyResults []Result
答案 1 :(得分:3)
I might be missing something, but why do you need Pipe
for this?
You probably could do it easier:
query := bson.M{"slug": slug, "companyusers.username": username}
err := c.Find(query).All(&companyResults)
I'm fairly certain this would give you the same results.
However, the main problem is you didn't give the bson marshaller the fields name. Since the field in your database is companyusers
and username
you'll have to tell that to the marshaller.
type Company struct {
Id bson.ObjectId `bson:"_id,omitempty"`
CompanyName string
Slug string
CompanyUsers []CompanyUser `bson:"companyuser"`
}
type CompanyUser struct {
UserName string `bson:"username"`
Email string
FullName string
}
You probably want to fix that for the rest of the fields as well.