2016-10-26 32 views
2

我在MongoDB中以下查詢 -蒙戈聚集查詢與氧化鎂司機

db.devices.aggregate({ 
$match: {userId: "v73TuQqZykbxFXsWo", state: true}}, 
{ 
    $project: { 
    userId: 1, 
    categorySlug: 1, 
    weight: { 
     $cond: [ 
     {"$or": [ 
      {$eq: ["$categorySlug", "air_fryer"] }, 
      {$eq: ["$categorySlug", "iron"] } 
     ] }, 
     0, 1] } 
    } }, 
    {$sort: {weight: 1}}, 
    { $limit : 10 } 
); 

我試圖使用氧化鎂司機golang寫這一點,但不能在所有的環繞此我的頭!

如何將其轉換爲golang mgo查詢?

+0

剛剛拆分每個階段和use'bson.M {}'環繞加上引號,像你查詢的每一窩級別:' match:= bson.M {「$ match」:bson.M {「userId」:「...」,...}}',然後'project:= bson.M {「$ project」...} '。現在,使用mgo driver'Pipe',像'pipe:= collection.Pipe([] bson.M {match,project})',最後用'pipe.All(&yourResultStruct)'檢索結果。閱讀他們的文檔'Pipe' [here](https://godoc.org/labix.org/v2/mgo#Collection.Pipe) – Anzel

回答

2

文檔上的示例足以開始使用。但是,如果您對golang不熟悉,那麼$cond部分可能會有點棘手。請參見下面的示例代碼:

collection := session.DB("dbName").C("devices") 

    stage_match := bson.M{"$match":bson.M{"userId":"v73TuQqZykbxFXsWo", "state": true}} 

    condition_weight := []interface{}{bson.M{"$or": []bson.M{ 
         bson.M{"$eq": []string{"$categorySlug", "air_fryer"}}, 
         bson.M{"$eq": []string{"$categorySlug", "iron"}}, 
    }}, 0, 1} 

    stage_project:= bson.M{"$project": bson.M{"userId":1, "categorySlug":1, "weight": condition_weight}} 

    stage_sort := bson.M{"$sort": bson.M{"weight":1}} 

    stage_limit := bson.M{"$limit": 10} 

    pipe := collection.Pipe([]bson.M{stage_match, stage_project, stage_sort, stage_limit}) 

參見mgo: type Pipe

+0

謝謝你的詳細解答。是的,你知道我不能正確翻譯聚合查詢中的各個部分。獎勵! –

+0

我需要在查詢中對此進行小修改 - http://stackoverflow.com/questions/27686914/behaviour-of-the-project-stage-operator-in-projecting-arrays爲了使它適用於我的情況。在stage_project中,'weight'參數需要定義爲「weight」:bson.M {「$ literal」:condition_weight} –