使用 mongoDB 在不同“列”中聚合特定字段的列表

在 Golang 上使用 mongo-driver。


为了保存 2 个实体之间的关系列表,我使用了一个集合,其中每个文档都有一个“uid1”和一个“uid2”,它们是每个实体的唯一标识符。任何实体都可以在两边。目标是找到与我选择的实体有关系的所有实体并将其放入列表中。目前通过做:


cursor, err := RelationsColl.Find(ctx, bson.M{"$or": []bson.M{bson.M{"uid1": UID}, bson.M{"uid2": UID}}})


    var res []bson.M

    if err = cursor.All(ctx, &res); err != nil {

        return nil, err

    }


我在变量中获得了变量res存在的条目列表UID。相反,我想要得到的只是一个在对应条目中包含 UID 的列表。因此,不要以以下形式获取某些东西:(假设我们请求与“xxxx”有关系的实体)


[[uid1:xxxx uid2:yyyy],[uid1:zzzz uid2:xxxx]]


我可以得到以下形式的东西:


[yyyy, zzzz]

这可能与聚合有关吗?


希望我很清楚,如果有任何未明确解释的内容,请在下面发表评论。


烙印99
浏览 176回答 1
1回答

白猪掌柜的

下面的代码应该为您解决问题UID := "id-1"  // Change this variable to your `match` valuematchStage := bson.D{    {"$match", bson.D{        {"$or", bson.A{            bson.D{{"uid1", UID}},            bson.D{{"uid2", UID}},        }},    }},}groupStage := bson.D{    {"$group", bson.D{        {"_id", nil},        {"uids1", bson.D{            {"$addToSet", "$uid1"},        }},        {"uids2", bson.D{            {"$addToSet", "$uid2"},        }},    }},}projectStage := bson.D{    {"$project", bson.D{        {"uids", bson.D{            {"$filter", bson.D{                {"input", bson.D{                    {"$concatArrays", bson.A{"$uids1", "$uids2"}},                }},                {"as", "arrayElem"},                {"cond", bson.D{                    {"$ne", bson.A{"$$arrayElem", UID}},                }},            }},        }},    }},}cursor, err := collection.Aggregate(    ctx,    mongo.Pipeline{matchStage, groupStage, projectStage},    options.Aggregate().SetAllowDiskUse(true),    )if err != nil {    panic(err)}var cursorResult []bson.Merr = cursor.All(ctx, &cursorResult)if err != nil {    panic(err)}fmt.Println("Cursor Result: ", cursorResult[0]["uids"])
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go