2016-09-28 3 views
0

私は、私は1つのコレクション内の2つのドキュメント持っ例えばgolangmgomongodb version is 3.2.9golang(mgo)を使用して、2つのmongodbクエリを1つのクエリで集計できますか?

を使用します。私はphoneNumber (value and name)を知っていると私は、電子メール(値)を見つける必要があり

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

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

を。 2つのクエリで簡単に行うことができます。最初にphoneNumberでgroupIdを見つけてからgroupIdでメールを見つけました。 golangとmgoを使用して1つのクエリで実行できますか?

答えて

0

はい、フォームの集約パイプラインを実行する必要があります:同等のMgO式が(未テスト)以下の

{ "email" : "[email protected]" } 

その

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); 

サンプル出力:

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() 
関連する問題