Anna
Anna

Reputation: 889

Mongodb: sort by elements in an array

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?

Upvotes: 1

Views: 3914

Answers (1)

Ashh
Ashh

Reputation: 46451

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
    }
  }
])

Upvotes: 2

Related Questions