-1
{"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"}

这是我的数据库中的一个样本,我想选择一个随机重播。

4

1 回答 1

3

虽然不是最有效的解决方案,但您可以执行以下操作:

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
      }
    });
  }
});

灵感来自MongoDB 的类似方法

请注意,此解决方案存在与上述相同的一些问题;即它不是很有效,并且如果在获取响应.count()和获取响应之间的记录数量发生变化,则会出现竞争条件.exec()。但是,在 NeDB 支持诸如$sample聚合之类的东西之前,我认为这是唯一的选择。

于 2017-05-06T21:52:56.947 回答