Random sort order

mongodb, mongodb-query

Solution

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

Example (untested):

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

Note, however, that – if using the older MMAPv1 storage engine – it may return the same document more than once.

Problem

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. 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(); ``` 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:) 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}); ``` 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}}); ``` Does anyone know about such features?

Original source

Related problems