MongoDB query to fetch random value using Map Reduce concept.

To fetch random values using Map Reduce in MongoDB, use the mapReduce() method combined with Math.random() to emit documents based on a probability threshold.

Syntax

db.collection.mapReduce(
    function() { if (Math.random() 

Sample Data

db.demo651.insertMany([
    {Value: 10},
    {Value: 20},
    {Value: 30},
    {Value: 40},
    {Value: 50},
    {Value: 60},
    {Value: 70},
    {Value: 80}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e9f0330e3c3cd0dcff36a57"),
        ObjectId("5e9f0332e3c3cd0dcff36a58"),
        ObjectId("5e9f0335e3c3cd0dcff36a59"),
        ObjectId("5e9f0337e3c3cd0dcff36a5a"),
        ObjectId("5e9f0339e3c3cd0dcff36a5b"),
        ObjectId("5e9f033be3c3cd0dcff36a5c"),
        ObjectId("5e9f033ee3c3cd0dcff36a5d"),
        ObjectId("5e9f0340e3c3cd0dcff36a5e")
    ]
}

Display All Documents

db.demo651.find();
{ "_id" : ObjectId("5e9f0330e3c3cd0dcff36a57"), "Value" : 10 }
{ "_id" : ObjectId("5e9f0332e3c3cd0dcff36a58"), "Value" : 20 }
{ "_id" : ObjectId("5e9f0335e3c3cd0dcff36a59"), "Value" : 30 }
{ "_id" : ObjectId("5e9f0337e3c3cd0dcff36a5a"), "Value" : 40 }
{ "_id" : ObjectId("5e9f0339e3c3cd0dcff36a5b"), "Value" : 50 }
{ "_id" : ObjectId("5e9f033be3c3cd0dcff36a5c"), "Value" : 60 }
{ "_id" : ObjectId("5e9f033ee3c3cd0dcff36a5d"), "Value" : 70 }
{ "_id" : ObjectId("5e9f0340e3c3cd0dcff36a5e"), "Value" : 80 }

Map Reduce Query for Random Selection

Define the map function with a 10% probability threshold ?

map = function() {
    if (Math.random() 

Define the reduce function to return the values ?

reduce = function(key, values) {
    return values;
}

Execute the mapReduce operation ?

db.demo651.mapReduce(map, reduce, { out: 'demo_651' });
{
    "result" : "demo_651",
    "timeMillis" : 1104,
    "counts" : {
        "input" : 8,
        "emit" : 1,
        "reduce" : 0,
        "output" : 1
    },
    "ok" : 1
}

View Random Results

db.demo_651.find();
{ "_id" : ObjectId("5e9f033be3c3cd0dcff36a5c"), "value" : { "_id" : ObjectId("5e9f033be3c3cd0dcff36a5c"), "Value" : 60 } }

Key Points

  • Math.random() gives each document a 10% chance of being selected
  • The map function emits documents randomly based on the probability threshold
  • The reduce function simply returns the values without modification
  • Results vary on each execution due to the random nature

Conclusion

Map Reduce with Math.random() provides a probabilistic approach to fetch random documents. Adjust the threshold value to control selection probability and use the output collection to access randomly selected records.

Updated on: 2026-03-15T03:16:41+05:30

336 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements