gpt4 book ai didi

mongodb - 我可以使用 golang (mgo) 在一个查询中聚合两个 mongodb 查询吗?

转载 作者:数据小太阳 更新时间:2023-10-29 03:26:34 27 4
gpt4 key购买 nike

我用的是golangmgomongodb版本是3.2.9

For example i have two documents in one collection:

{"groupId" : 4, "name" : "email", "value" : "11@11.com"}

{"groupId" : 4,"name" : "phoneNumber","value" : "000000000"}

我知道 phoneNumber(值和名称),我需要找到电子邮件(值)。它可以通过两个查询简单地完成:首先通过 phoneNumber 我找到了 groupId 然后通过 groupId 我找到了电子邮件。是否可以在一个查询中完成(使用 golang 和 mgo)?

最佳答案

是的,您需要运行以下形式的聚合管道:

var pipeline = [    
{
"$group": {
"_id": "$groupId",
"entries": {
"$push": {
"name": "$name",
"value": "$value"
}
}
}
},
{
"$match": {
"entries.name" : "phoneNumber",
"entries.value" : "000000000"
}
},
{
"$project": {
"item": {
"$arrayElemAt": [
{
"$filter": {
"input": "$entries",
"as": "item",
"cond": { "$eq": [ "$$item.name", "email" ] }
}
}, 0
]
}
}
},
{
"$project": {
"_id": 0,
"email": "$item.value"
}
}

]);
db.collection.aggregate(pipeline);

示例输出

{ "email" : "11@11.com" }

其中等效的 mGo 表达式如下(未经测试):

pipeline := []bson.D{   
bson.M{
"$group": bson.M{
"_id": "$groupId",
"entries": bson.M{
"$push": bson.M{
"name": "$name",
"value": "$value"
}
}
}
},
bson.M{
"$match": bson.M{
"entries.name" : "phoneNumber",
"entries.value" : "000000000"
}
},
bson.M{
"$project": bson.M{
"item": bson.M{
"$arrayElemAt": [
bson.M{
"$filter": bson.M{
"input": "$entries",
"as": "item",
"cond": bson.M{ "$eq":
[]interface{}{ "$$item.name", "email" }
}
}
}, 0
]
}
}
},
bson.M{
"$project": bson.M{
"_id": 0,
"email": "$item.value"
}
}
}

pipe := collection.Pipe(pipeline)
iter := pipe.Iter()

关于mongodb - 我可以使用 golang (mgo) 在一个查询中聚合两个 mongodb 查询吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39747073/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com