query random items with mongoose in javascript

To randomly select items from a collection using Mongoose, you can use the aggregate method and the $sample operator.

Here is an example of how to do it:

index.tsx
const Model = require('./models/modelName');

Model.aggregate([{ $sample: { size: 10 } }])
  .then(randomItems => {
    console.log(randomItems);
  })
  .catch(error => {
    console.error(error);
  });
203 chars
10 lines

In this example, we are selecting 10 random items from the modelName collection using $sample operator. You can change the size to any value as per your requirement.

Note: The $sample operator is only available in MongoDB version 3.2 or later. So, make sure you are using a compatible version of MongoDB.

related categories

gistlibby LogSnag