2016-09-28 146 views
0

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

例如我有一个收集两个文件:

{"groupId" : 4, "name" : "email", "value" : "[email protected]"} 

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

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

回答

0

是的,你需要运行形式的聚合管道:

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" : "[email protected]" } 

这相当于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() 
相关问题