1

I am working on a project and I found a request that I don't understand and is not working. We have documents that look like this:

 {
        "id": ObjectId("6457959757555445"),
        "buyer" : { 
            "id": ObjectId("588888815654684")      
            "roles" : [ 
                "BUYER"
            ]
        }
},
{
        "id": ObjectId("6457959707555445"),
        "buyer" : { 
            "id": ObjectId("588800015654684")      
            "roles" : [ 
                "ADMIN"
            ]
        }
}

And there is a request that should sort a collection of theses documents by roles. So for the example above, I will have ADMIN then BUYER. So here is the request:

{  
   "aggregate":"__collection__",
   "pipeline":[  
      {  
         "$sort":{  
            "buyer.roles":1
         }
    },
}

Should we really use pipeline here? and why it is not working?

8
  • Hi.Can you explain better what you want to obtain? roles is an array. How to sort something by an array? Commented Jul 10, 2018 at 11:42
  • Hi. Yes that's what I want to do. Commented Jul 10, 2018 at 11:49
  • Do you need to sort with role name that is "ADMIN" will come first and "BUYER" will second? Commented Jul 10, 2018 at 11:50
  • @AnthonyWinzlet Yes exactly Commented Jul 10, 2018 at 11:51
  • So what if "roles" : [ "ADMIN", "BUYER" ] ? Commented Jul 10, 2018 at 11:51

1 Answer 1

2

You need to first $unwind "roles" array and then you can easily apply $sort on "roles"

db.collection.aggregate([
  {
    $unwind: "$buyer.roles"
  },
  {
    $sort: {
      "buyer.roles": 1
    }
  }
])
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.