mongo聚合查询在golang与mgo驱动程序

编程入门 行业动态 更新时间:2024-10-22 17:23:38
本文介绍了mongo聚合查询在golang与mgo驱动程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在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驱动程序在golang中编写此代码,但无法绕过我的头这是所有!

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

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

How do I translate this to a golang 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:type Pipe

更多推荐

mongo聚合查询在golang与mgo驱动程序

本文发布于:2023-11-22 15:07:24,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:驱动程序   mongo   golang   mgo

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!