使用mgo驱动程序在golang中进行mongo聚合查询

Gau*_*jha 4 go mongodb mgo aggregation-framework mongodb-aggregation

我在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 }
);
Run Code Online (Sandbox Code Playgroud)

我正在尝试使用mgo驱动程序在golang中编写这个,但根本无法解决这个问题!

如何将其翻译为golang mgo查询?

Wan*_*iar 6

文档上的示例就足以开始了.但是,如果你不熟悉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})
Run Code Online (Sandbox Code Playgroud)

另请参见mgo:type Pipe