2016-10-26 14 views
2

I가 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" '. 이제'pipe : = collection.Pipe ([] bson.M {match, project})'와 같이 그것들과 함께 mgo 드라이버'Pipe'를 사용하고, 마지막으로'pipe.All (& yourResultStruct)'로 결과를 검색합니다. 'Pipe'의 문서보기 [여기] (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} –