mongo aggregation query in golang with mgo driver

China☆狼群 提交于 2019-12-23 12:06:54

问题


I have the following query in 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 }
);

I'm trying to write this in golang using the mgo driver but not able to wrap my head around this at all!

How do I translate this to a golang mgo query?


回答1:


The examples on the docs would be sufficient to get started. However, if you are not familiar with golang, the $cond part could be a bit tricky. See below example code:

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

See also mgo: type Pipe



来源:https://stackoverflow.com/questions/40259171/mongo-aggregation-query-in-golang-with-mgo-driver

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!