How to sort a MongoDB collection by field in an embedded document using Mongoid?

I want to run this query using Mongoid:

db.users.find().sort({'users.roles.name':1})

How will it look in Mongoid? Or maybe there is an easy way to get Mongoid to execute this custom request?

+5
source share
3 answers

First of all, you can answer one simple question: how to sort documents by array? Yes, I don’t know either ..

I believe that you can sort by a specific role using the positioning operator:

db.users.find().sort({'roles.0.name':1})

But I am not sure and I can not check it correctly, and mb is not quite what you need. In any case, you can test and return with the results, otherwise I will find out tomorrow.

+5

User.asc("roles.name") .

+4

:

db.users.find().sort("{\"roles\":{\"name\":1}}");
+1

All Articles