MongoDB 管道中的多个顶级聚合查询

Multiple top level aggregate queries in a MongoDB Pipeline

我有以下查询:

match := bson.D{{"$match", bson.D{{"venue", venueID}}}}
group := bson.D{{"$lookup", bson.M{
    "from":         "labels",
    "localField":   "label_ids",
    "foreignField": "_id",
    "as":           "labels",
}}, {"$graphLookup", bson.M{
    "from":             "menus",
    "startWith":        "$child_ids",
    "connectFromField": "child_ids",
    "connectToField":   "_id",
    "as":               "children",
    "maxDepth":         5,
    "depthField":       "level",
}}}

cur, err := m.collection.Aggregate(ctx, mongo.Pipeline{group, match})

我有两个相关的字段,其中一个是图形结构(菜单),每个父元素都有一个用于每个子元素的 ID 数组。

第二个字段 labels 只是一对多查询。标签和菜单应该是可重复使用的,因此不会嵌入到单个父实体中。上面概述的查询对我来说很有意义,但是我收到以下错误:

A pipeline stage specification object must contain exactly one field.

谢谢!

MongoDB 管道中的每个元素都必须是单级的,例如$match$group

您的 group 元素包含 2 个阶段:$lookup$graphLookup

将它们拆分并单独列出:

match := bson.D{{"$match", bson.D{{"venue", venueID}}}}
group := bson.D{{"$lookup", bson.M{
    "from":         "labels",
    "localField":   "label_ids",
    "foreignField": "_id",
    "as":           "labels",
}}}
graphLookup := bson.D{{"$graphLookup", bson.M{
    "from":             "menus",
    "startWith":        "$child_ids",
    "connectFromField": "child_ids",
    "connectToField":   "_id",
    "as":               "children",
    "maxDepth":         5,
    "depthField":       "level",
}}}

cur, err := m.collection.Aggregate(ctx, mongo.Pipeline{group, graphLookup, match})