使用 MongoMapper 根据数组的大小对 MongoDB 中的项目进行排序?
我想选择根据数组中的项目数量排序的项目集合。希望下面的示例能够澄清我相当糟糕的解释:
class Thing
include MongoMapper::Document
key :name, String
key :tags, Array
end
我想检索从标签最多到标签最少的所有 Thing
。此示例中的标签只是标签数组中的字符串。基本上我想要的东西与此含义相同(但有效):
Thing.all(:order => 'tags.count desc')
这可能吗?
I'd like to select a collection of items ordered based on the number of items within an array. Hopefully the following example will clarify my rather poor explanation:
class Thing
include MongoMapper::Document
key :name, String
key :tags, Array
end
I'd like to retrieve all Thing
s ordered from those with the most tags to those with the least. The tags in this example are simply strings within the tags array. Basically I want something which means the same as this (but works):
Thing.all(:order => 'tags.count desc')
Is this possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
核心服务器当前不支持计算数组的大小,然后按该大小进行排序。我认为目前最好的选择是自己缓存数组大小,并在该字段上添加索引。
然后只需向您的模型添加一个回调,以在保存时更新 tag_size 。
如果这是您希望在核心服务器中看到的功能,您可以在此处添加一个案例:
http ://jira.mongodb.org/browse/SERVER
The core server currently doesn't support computing the size of an array and then sorting by that. I think that your best bet for the moment would be to cache the array size on your own, and add an index on that field.
Then just add a callback to your model that updates tag_size on save.
If this is a feature you'd like to see in the core server, you can add a case here:
http://jira.mongodb.org/browse/SERVER