Ayman Elmalah
Ayman Elmalah

Reputation: 331

Custom sort 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

Upvotes: 2

Views: 597

Answers (1)

zangw
zangw

Reputation: 48436

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)

Upvotes: 1

Related Questions