I need to get only 4 documents from MongoDB by node/express.js . I can make the limit for the 4 documents but not for random 4 . SO, how can I get 4 random documents?
            Asked
            
        
        
            Active
            
        
            Viewed 233 times
        
    0
            
            
        - 
                    1https://mongoplayground.net/p/vGzRcV3e2yb – cmgchess Jan 17 '22 at 09:38
1 Answers
0
            Starting with the 3.2 release of MongoDB, you can get N random docs from a collection using the $sample aggregation pipeline operator:
// Get one random document from the mycoll collection.
db.mycoll.aggregate([{ $sample: { size: 1 } }])
If you want to select the random document(s) from a filtered subset of the collection, prepend a $match stage to the pipeline:
// Get one random document matching {a: 10} from the mycoll collection.
db.mycoll.aggregate([
    { $match: { a: 10 } },
    { $sample: { size: 1 } }
])
When size is greater than 1, there may be duplicates in the returned document sample.
 
    
    
        Sughosh Pandey
        
- 72
- 3
