2

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 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.