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

Gaurav Ojha:

我在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驱动程序在golang中编写此代码,但根本无法解决这个问题!

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

Wan Bachtiar:

文档上的示例足以开始。但是,如果您不熟悉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:管道类型

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

使用Java的Mongo 3.2驱动程序的新聚合功能

聚合查询中的Mongodb Java驱动程序使用限制

使用Java驱动程序进行MongoDB聚合

使用本机驱动程序附加到mongo查询

使用C#mongo驱动程序构建查询

Golang mongo驱动程序性能

是否可以使用mgo驱动程序运行mongo copysetset命令?

使用mgo驱动程序,Mongo连接计数每10秒爬行一次

使用golang和sqlserver驱动程序查询参数

使用 Python Cassandra 驱动程序进行大号。查询数

如何使用golang mgo MongoDb驱动程序获取最后插入的ObjectId

如何在Golang中使用mgo编写以下Mongo聚合查询

用于更新的 Mongo Db 驱动程序 C# 聚合

在带有mgo驱动程序的Upsert上使用$ setOnInsert

使用mgo驱动程序的MongoDB管理员命令

使用phantomjs驱动程序C#在Selenium中进行代理

如何使用驱动程序在MongoDB中进行文档版本控制

使用Java驱动程序对MongoDB聚合查找阶段的结果进行排序

使用ProjectionDefinition和C#驱动程序进行Mongodb组聚合

通过 C# MongoDB 驱动程序聚合查询结果

MongoDB聚合查询通过C#驱动程序变慢

如何使用 mongo 驱动程序在 Golang 中实现 MongoDB 自动完成?

如何使用2.4 C#Mongo驱动程序运行解释查询?

如何使用mongo java驱动程序将实际查询记录到MongoDB

避免使用构建器在查询中更改 mongo 驱动程序的日期

使用FindAndModify在官方的Mongo Go驱动程序中运行查询

C#Mongo驱动程序:使用联接和UpdateManyAsync更新查询

如何使用Mongo-Java驱动程序运行MongoDB本机查询(JSON)?

如何使用Mongo Java驱动程序与索引交集编写查询