随机排序 [英] Random sort order

查看:39
本文介绍了随机排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于从集合中获取随机文档的方式的问题已经被问过很多次了,并且有关于这个话题的建议.

The question about the way to get a random document from collection has been asked many times and there were suggestions on this topic.

我需要的是从集合中获取几个随机文档,更糟糕的是 - 这些文档必须符合某些标准(过滤,我的意思是).例如,我有一个文章集合,其中每篇文章都有一个主题"字段.用户选择一个他感兴趣的主题,我的数据库每次都必须以随机顺序显示相应的文章.

What I need is to get several random documents from collection and what is even worse - those documents must match certain criterias (filtered, I mean). For example, I have a collection of articles where each article has a 'topic' field. The User chooses a topic he's interested in, and my db must show the corresponding articles each time in random order.

显然,之前讨论的 hack 对我没有帮助.实现我想要的唯一方法是查询仅获取 id 的相应主题:

Obviously, previously discussed hacks won't help me. The only way to achieve what I want is to query for corresponding topic getting ids only:

var arr = db.articles.find({topic: 3}, {_id:1}).toArray();

然后根据收到的文档数量生成随机数字序列,然后使用随机数作为该数组的索引从数组中获取文档 id,然后最后向 mongodb 发出另一个请求以获取具有这些随机选择的 id 的文档.

and then generate random sequense of numbers depending on how many documents were received and then obtain document ids from the array using random numbers as indexes of that array and then finally do another request to mongodb to obtain documents with those randomly chosen ids.

正如你所看到的,这似乎有点太慢了,特别是如果第一次查询返回的文章太多:)

As you can see, it seems a little bit too slow altogether, especially, if there are too many articles returned by first query:)

所以我认为可能有一些 mongodb 命令根据它们在索引中的位置通过索引键获取文档.关键是我可以像这样创建覆盖的复合索引:

So what I think is that there may be some mongodb command to get documents by index keys based on their position in the index. The point is that I can create covered compound index like this:

db.articles.ensureIndex({topic: 1, _id:1});

现在我的查询只需要扫描索引中右侧 _ids 的连续行.如果我可以通过那些_ids"位置从集合中请求文档,那么我可以在一个请求中完成整个事情!类似的东西:

And now my query would only have to scan the continuos line of right _ids in index. And if I could request the documents from the collection by those '_ids' positions, then I could do the whole thing in one request! Something like:

var cursor = db.articles.find({topic:3, $indexKeyPosition: {$in: myRandomSequence}});

有人知道这些功能吗?

推荐答案

如今,您应该能够使用 $sample 聚合函数.

Nowadays, you should be able to use the $sample aggregation function.

示例(未经测试):

db.articles.aggregate([
    { $match : { topic : 3 } },
    { $sample : { size: 3 } }
])

但是请注意,它可能会多次返回同一个文档.

Note, however, that it may return the same document more than once.

这篇关于随机排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆