To query 10% of the eligible documents at random in a MongoDB database, you can use the following steps:

  1. Determine the total number of eligible documents in the collection by using the count() method:
var totalDocs = db.collection.count({<query>});

Replace <query> with the query that specifies the eligibility criteria for the documents.

  1. Calculate the number of documents to retrieve by multiplying the total number of documents by 0.1:
var numDocs = Math.ceil(totalDocs * 0.1);

Use Math.ceil() to round up the result to the nearest integer.

  1. Generate a random offset value between 0 and the total number of documents minus the number of documents to retrieve:
var offset = Math.floor(Math.random() * (totalDocs - numDocs));

Use Math.floor() to round down the result to the nearest integer.

  1. Use the find() method with the skip() and limit() methods to retrieve the random sample of documents:
var docs = db.collection.find({<query>}).skip(offset).limit(numDocs);

Replace <query> with the same query used in step 1.

The skip() method skips the first offset documents and the limit() method retrieves the next numDocs documents. The result is a cursor object that you can iterate over to access the documents in the sample.

Note that this method may not be suitable for very large collections, as it requires scanning the entire collection to calculate the total number of documents. In such cases, you may need to use a different sampling method, such as reservoir sampling

How to query 10 of the eligible documents at random in a MongoDB database

原文地址: https://www.cveoy.top/t/topic/fPWD 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录