在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]
这可能与聚合有关吗?希望我很清楚,如果没有任何明确说明的内容,请在下面评论。
最佳答案
下面的代码应该为您解决问题
UID := "id-1" // Change this variable to your `match` value
matchStage := 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.M
err = cursor.All(ctx, &cursorResult)
if err != nil {
panic(err)
}
fmt.Println("Cursor Result: ", cursorResult[0]["uids"])
关于mongodb - 使用mongoDB汇总不同 “columns”中特定字段的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62699208/