Random record from MongoDB

后端 未结 27 1909
栀梦
栀梦 2020-11-22 01:22

I am looking to get a random record from a huge (100 million record) mongodb.

What is the fastest and most efficient way to do so? The data is already t

27条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-22 01:38

    In order to get a determinated number of random docs without duplicates:

    1. first get all ids
    2. get size of documents
    3. loop geting random index and skip duplicated

      number_of_docs=7
      db.collection('preguntas').find({},{_id:1}).toArray(function(err, arr) {
      count=arr.length
      idsram=[]
      rans=[]
      while(number_of_docs!=0){
          var R = Math.floor(Math.random() * count);
          if (rans.indexOf(R) > -1) {
           continue
            } else {           
                     ans.push(R)
                     idsram.push(arr[R]._id)
                     number_of_docs--
                      }
          }
      db.collection('preguntas').find({}).toArray(function(err1, doc1) {
                      if (err1) { console.log(err1); return;  }
                     res.send(doc1)
                  });
              });
      

提交回复
热议问题