我用的是golang
和mgo
,mongodb版本是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/