mongodb - 使用mongoDB汇总不同 “columns”中特定字段的列表

标签 mongodb go aggregation

在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/

相关文章:

mongodb - 在 MongoDB 聚合框架中计算中位数

go - 需要与Makefile一起使用多个Go版本

kendo-ui - Kendo 网格 - 单行中的汇总字段

java - 如何在 Spring Boot 中使用特定日期范围和聚合从 MongoDB 数据库检索数据?

javascript - Nodejs - 获取 Mongoose typescript 错误

javascript - 使用 Cloud9 IDE - 尝试连接到我的 mongodb

arrays - 附加到数组后我无法修改该项目

go - 无法弄清楚为什么这个循环是数据竞争

c++ - 在构造函数中调用类成员的构造函数

node.js - req.body 在放置请求时返回空对象