英文:
Custom sort Golang mongodb
问题
我有一个具有以下模式的订单表:
SKU | 状态 |
---|---|
1 | 进行中 |
2 | 已交付 |
3 | 正在交付 |
我需要按照自定义的方式对订单进行排序,使得进行中的订单首先显示,然后是正在交付的订单,最后是已交付的订单。
当前的查询语句需要进行改进:
options.setSort(bson.D({"status", -1}))
model.Collection.Find(ctx, filter, options)
如何使模型按照这个自定义排序进行排序?
我正在使用Golang和MongoDB驱动程序。
英文:
I have orders table with schema
SKU | status |
---|---|
1 | IN_PROGRESS |
2 | DELIVERED |
3 | ON_DELIVERY |
I need to sort orders with custom way
so the in progress orders come first, then on delivery and finally delivered orders
the current query but need to be enhanced is
options.setSort(bson.D({"status", -1}))
model.Collection.Find(ctx, filter, options)
How to make model sort with this custom sort
I'm using golang with mongodb driver
答案1
得分: 1
一种选项是使用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)
英文:
One option is to do custom sort by aggregate cond
Mongo query is
db.products.aggregate([
{"$project":{
"sortField":
{"$cond":[{"$eq":["$status", "IN_PROGRESS"]}, 1,
{"$cond":[{"$eq":["$status", "ON_DELIVERY"]}, 2,
3]} ]},
"status": true
}},
{"$sort":{"sortField": 1}}
]);
For collection data
db.products.insertMany([{"sku": 1, "status": "IN_PROGRESS"}, {"sku": 2, "status": "DELIVERED"}, {"sku": 3, "status": "ON_DELIVERY"}]);
Output
[
{
"sortField": 1,
"status": "IN_PROGRESS"
},
{
"sortField": 2,
"status": "ON_DELIVERY"
},
{
"sortField": 3,
"status": "DELIVERED"
}
]
And for golang mongo driver
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论