0
{"message":"hi","replay":"hello","messageFrom":253505936,"_id":"RFxx2j5jiHfvT7F8"}
{"message":"what is your name","replay":"kokokoko","messageFrom":322078970,"_id":"49leUECRRWrWdVc1"}
{"message":"no why","replay":"don't ask me","messageFrom":322078970,"_id":"7bb8DXqYTsPwq12n"}
{"message":"thank you","replay":"you'r welcome","messageFrom":200826832,"_id":"KrgmVquPDyqM6o7Z"}

this is a sample from my DB and I want to pick a random replay.

tavnab
  • 2,594
  • 1
  • 19
  • 26
Engineer Passion
  • 1,051
  • 1
  • 8
  • 14
  • 2
    I suspect the downvotes are because you haven't shown what you tried & where you're having trouble. Check out https://stackoverflow.com/help/how-to-ask to avoid this in the future. – tavnab May 06 '17 at 21:54

1 Answers1

4

While not the most efficient solution, you can do something like this:

db.count({}, function (err, count) {
  if (!err && count > 0) {
    // count is the number of docs

    // skip a random number between 0 to count-1
    var skipCount = Math.floor(Math.random() * count);

    db.find({}).skip(skipCount).limit(1).exec(function (err2, docs) {
      if (!err2) {
        // docs[0] is your random doc
      }
    });
  }
});

Inspired by a similar approach for MongoDB.

Note that this solution suffers some of the same issues as the above; namely that it's not very efficient, and that there's a race condition if the number of records have changed between the getting the response to .count() and getting the response to .exec(). However, until NeDB supports something like $sample aggregation, I think this is the only option.

Community
  • 1
  • 1
tavnab
  • 2,594
  • 1
  • 19
  • 26