Get random documents from PouchDB (or CouchDB)
I am developing a quiz app with Angular and Ionic. I have about 2000 questions in json format and I choose PouchDB as my database. CouchDB works great for me: I can add new question to question and answer to auto question and server.
But now I have a doubt: I cannot find a way to get random documents from Pouch. With my application, I will create quizzes from a specific highlighted section and I have to get a variable number of documents from my DB.
I am using db.allDocs([options], [callback])
api, I can set a limit, but I cannot find a way to get a random document.
Is there any solution?
source to share
The first solution given by @nlawson doesn't always work, for example I had to delete every document so that I lost the sequence of IDs, like this:
I had a list of documents with IDs 1 to 5
1- random = 3
2- get document with id 3
3- delete document with ID 3 Database status [1,2,4,5]
4- if random is something other than three repetitions above, but if the random value is 3 or any id already removed, it causes problems, so this solution doesn't work, so I found another solution which is:
ANSWER:
Using Mango querie find (), with this code
let rand = Math.floor(Math.random() * (max - min + 1)) + min;
db.find({
selector: {_id: {$gte : '1'}},
limit : 1,
skip : rand-1,
});
First of all, I get a random number, the maximum number of documents in my database, and min is 1 as the first ID given in the first document.
After that, I run a find () query to select documents with id greater than or equal to 1 (basically all), restricts the query to only fetch the first, and start fetching from rand-1.
To reuse our first example with rand equal to 3, it would be something like this:
1- get all documents with ID greater than or equal to 1 => [1,2,3,4,5]
2- starting at rand-1 witch 3-1 = 2 gets a limited number of documents, limit is 1 => [2]
Therefore, it will always return the document at the rand position.
PS: to use find () you have to install this pouchdb.find.js library over the package
source to share
You could
-
Give your documents
_id
from '1', '2', '3', etc. and then useMath.random()
toget()
one at random. -
Or, you can read in all ids with bulkDocs and then pick one at random for
get()
, but this can be bad for performance if you have a lot of documents:
db.allDocs().then(function (res) {
var ids = res.rows.map(function (row) { return row.id; });
var index = Math.floor(Math.random() * ids.length);
return db.get(ids[index]);
}).then(function (randomDoc) {
// you got a randomDoc
}).catch(console.log.bind(console))
source to share