开发者

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

开发者 https://www.devze.com 2023-02-13 23:49 出处:网络
I want to run this query using Mongoid: db.users.find().sort({\'users.roles.name\':1}) What will that look like in Mongoid? Or maybe there is an easy way to have Mongoid just execute that c开发者_J

I want to run this query using Mongoid:

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

What will that look like in Mongoid? Or maybe there is an easy way to have Mongoid just execute that c开发者_JAVA技巧ustom query?


First of all can you answer to the one simple question: How to sort documents by array? Yes, i also don't know..

I suppose that you can sort by specific role, using positional operator:

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

But i am not sure and can't test it right know and mb it's not exactly what you need. In any way you can test and come back with results, otherwise i will figure out it tomorrow.


User.asc("roles.name") should do it for you.


This will work:

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

精彩评论

暂无评论...
验证码 换一张
取 消