使用mgo驱动程序的mongo聚合查询 [英] mongo aggregation query with mgo driver

查看:117
本文介绍了使用mgo驱动程序的mongo聚合查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在mongodb中有以下查询:

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

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

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

如何将其转换为Go mgo查询?

How do I translate this to a Go mgo query?

推荐答案

文档中的示例足以开始使用.但是,如果您不熟悉golang,则 $ cond 部分可能会有些棘手.参见下面的示例代码:

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

另请参见 mgo:输入管道

这篇关于使用mgo驱动程序的mongo聚合查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆