Golang中使用自定义排序功能查询MongoDB
时间:2024-02-29
浏览:501
作者:佚名
在Golang实战开发的过程中,我们经常会遇到一些这样那样的问题,然后要卡好半天,等问题解决了才发现原来一些细节知识点还是没有掌握好。今天golang学习网就整理分享《Golang中使用自定义排序功能查询MongoDB》,聊聊,希望可以帮助到正在努力赚钱的你。
问题内容
我有带有架构的订单表
| SKU | status |
|---|---|
| 1 | IN_PROGRESS |
| 2 | DELIVERED |
| 3 | ON_DELIVERY |
我需要以自定义方式对订单进行排序 因此,首先是进行中的订单,然后是交付中的订单,最后是交付的订单
当前但需要增强的查询是
options.setsort(bson.d({"status", -1}))
model.collection.find(ctx, filter, options)
如何使用此自定义排序进行模型排序
我正在使用 golang 和 mongodb 驱动程序
正确答案
一种选择是按 aggregate cond 进行自定义排序
mongo 查询是
db.products.aggregate([
{"$project":{
"sortfield":
{"$cond":[{"$eq":["$status", "in_progress"]}, 1,
{"$cond":[{"$eq":["$status", "on_delivery"]}, 2,
3]} ]},
"status": true
}},
{"$sort":{"sortfield": 1}}
]);
用于收集数据
db.products.insertmany([{"sku": 1, "status": "in_progress"}, {"sku": 2, "status": "delivered"}, {"sku": 3, "status": "on_delivery"}]);
输出
[
{
"sortfield": 1,
"status": "in_progress"
},
{
"sortfield": 2,
"status": "on_delivery"
},
{
"sortfield": 3,
"status": "delivered"
}
]
对于 golang mongo 驱动程序
pipeline := []bson.M{
{"$project": bson.M{"sortField":
bson.M{"$cond": bson.A{bson.M{"$eq": bson.A{"$status", "IN_PROGRESS"}}, 1,
bson.M{"$cond": bson.A{ bson.M{"$eq": bson.A{"$status", "ON_DELIVERY"}}, 2, 3}} }},
"status": true}},
{"$sort": bson.M{"sortField": 1}},
}
model.Collection..Aggregate(context.Background(), pipeline)以上就是《Golang中使用自定义排序功能查询MongoDB》的详细内容,更多关于的资料请关注golang学习网公众号!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.20
11.20
11.20
11.20
热门专题
