MongoDB query to fetch random value using Map Reduce concept.

MongoDBDatabaseBig Data Analytics

For random value with Map Reduce, use mapReduce() concept along with Math.random(). Let us create a collection with documents −

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

Display all documents from a collection with the help of find() method −

> db.demo651.find();

This will produce the following output −

{ "_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 }

Following is the query to fetch data −

> map = function() {
...
...    if (Math.random() < 0.1) {
...       emit(this._id, this);
...    }
... }
function () {
   if (Math.random() < 0.1) {
      emit(this._id, this);
   }
}
>
> reduce = function(key, values) {
... return values;
... }
function (key, values) {
   return values;
}
>
> db.demo651.mapReduce( map, reduce, { out: 'demo_651' } );
{
   "result" : "demo_651",
   "timeMillis" : 1104,
   "counts" : {
      "input" : 8,
      "emit" : 1,
      "reduce" : 0,
      "output" : 1
   },
   "ok" : 1
}
> db.demo_651.find();

This will produce the following output −

{ "_id" : ObjectId("5e9f033be3c3cd0dcff36a5c"), "value" : { "_id" : ObjectId("5e9f033be3c3cd0dcff36a5c"), "Value" : 60 } }
raja
Published on 12-May-2020 09:00:09

Advertisements