go - 带有 $lookup 查询的 MGO Pipe 不会附加“已加入”集合中的匹配文档
问题描述
我的模特
type (
//Category implements item category in database
Category struct {
ID bson.ObjectId `bson:"_id,omitempty" json:"id"`
Name string `bson:"name" json:"name" form:"name" valid:"Required"`
IsActive bool `bson:"is_active" json:"is_active" form:"is_active" valid:"Required"`
Slug string `bson:"slug" json:"slug"`
Icon string `bson:"icon" json:"icon" form:"icon"`
SidebarIcon string `bson:"sidebar_icon" json:"sidebar_icon" form:"sidebar_icon"`
Parent bson.ObjectId `bson:"parent,omitempty" json:"parent,omitempty" form:"parent"`
CreatedAt time.Time `bson:"created_at" json:"-"`
UpdatedAt time.Time `bson:"updated_at" json:"-"`
IsDeleted bool `bson:"is_deleted" json:"-"`
}
)
我的收集查询:
categories := []models.Category{}
f := func(collection *mgo.Collection) error {
query := []bson.M{
{
"$match": bson.M{
"is_deleted": bson.M{
"$ne": true,
},
},
},
{
"$sort": bson.M{
orderBy: pipeOrder,
},
},
{
"$limit": limit,
},
{
"$skip": skip,
},
{
"$lookup": bson.M{
"from": "categories",
"localField": "_id",
"foreignField": "parent",
"as": "parentlist",
},
},
}
return collection.Pipe(query).All(&categories)
目标:如果父 id 与集合中的文档之一匹配,则检索所有类别及其父类别。
问题:检索到所有类别但缺少“父列表”连接属性
堆栈:mgo 与 DB 和 golang 版本 1.8 交互
解决方案
在您的聚合中,您查找父级,它们将存储在一个名为parentlist
. 并且您尝试将结果解组为 的切片Category
,但该类型Category
没有匹配的字段parentlist
。因此,该字段将在解组过程中“丢失”。
有很多方法可以获得额外的parentlist
,一些可能性在这个答案中有详细说明:Mgo 聚合:如何重用模型类型来查询和解组“混合”结果?
一种选择是使用这样的包装器结构:
type CategoryWithParents struct {
Category models.Category `bson:",inline"`
Parents []*models.Category `bson:"parentlist"`
}
并解组成这样的一部分:
var results []CategoryWithParents
err := collection.Pipe(query).All(&results)
这将得到所有的父母。
如果所有类别最多只有一个父级,则可以将聚合修改为$unwind
,parentlist
并且Parents
可以是单个*model.Category
而不是切片:
type CategoryWithParents struct {
Category models.Category `bson:",inline"`
OptionalParent *models.Category `bson:"parentlist"`
}
var results []CategoryWithParents
f := func(collection *mgo.Collection) error {
query := []bson.M{
{
"$match": bson.M{
"is_deleted": bson.M{
"$ne": true,
},
},
},
{
"$sort": bson.M{
orderBy: pipeOrder,
},
},
{"$limit": limit},
{"$skip": skip},
{
"$lookup": bson.M{
"from": "categories",
"localField": "_id",
"foreignField": "parent",
"as": "parentlist",
},
},
{
"$unwind": bson.M{
"path": "parentlist",
"preserveNullAndEmptyArrays": true,
},
},
}
return collection.Pipe(query).All(&results)
}
推荐阅读
- apache-spark - EMR-5.32.0 上的 Spark 未生成请求的执行程序
- jsf - 如何重置 PrimeFaces 动态列的排序?
- sql-server - 包含嵌套对象的 XML 存在问题到 POCO(反)序列化(VB.Net)
- python - 获取TypeError:**或pow()不支持的操作数类型:'builtin_function_or_method'和'int'在Python中求解方程时
- postgresql - 编写一个触发器函数以根据 postgresql 中同一表中的另一个列值更新列值
- typo3 - TYPO3 9.5 扩展生成器抛出异常
- regex - 在电话号码 077 12345678 中包含空格
- excel - VBA 错误 1004 选择工作表范围失败
- python - 创建接收实时异步提要的 Python 数据可视化网站的方法
- c - 我可以将 NULL 传递给 modf/modff 吗?