Hello team,
How can I implement the below logic in mongo 4.4 with $function, $expr, $where. Is there an option to define global variable to be used across multiple records in 4.4 version. Below is the example I tried with MR in 4.2 version.
Since MR will be deprecated starting with v5.0. I’m trying to migrate the below logic as java script function in v4.4. I couldn’t find options with mongo aggregate to implement the below use case without adding transactions to an array. But the problem with this idea is it could run into 16 MB limitation if the volume of participating transactions is high.
data set
db.places.insertMany([
{ userid: "a", "location": "Bishan"},
{ userid: "b", "location": "Bukit Timah"},
{ userid: "c", "location": "Ang Mo Kio"},
{ userid: "d", "location": "Segar"},
{ userid: "e", "location": "Fajar"},
{ userid: "f", "location": "dover" },
{ userid: "g", "location": "Buona Vista"},
{ userid: "h", "location": "Marina Bay"},
{ userid: "i", "location": "Rocher"},
{ userid: "j", "location": "down town"},
{ userid: "k", "location": "Jurong"},
{ userid: "l", "location": "Pungol"},
{ userid: "m", "location": "One North"},
{ userid: "n", "location": "Cho Chu Kang"},
{ userid: "o", "location": "Yishun"}
]);
The below MR picks all records in a collection groups and classifies the records into multiple batches. i.e., “5” in each batch.
Global variables:
var counter = 0;
var batch = 1;
var threshold = 5;
Map Function:
var mapFunction = function() {
var key = this.userid;
if(counter >= threshold){
batch = batch+1;
counter = 0;
}
counter = counter +1;
var value = { location: this.location, batch: batch };
emit( key, value );
};
Reduce Function:
var reduceFunction = function(key, value) {
};
MR
db.places.mapReduce(
mapFunction,
reduceFunction,
{
out: "places_RV",
scope: {
batch : batch,
counter: counter,
threshold : threshold
}
}
)
Results
MongoDB Enterprise > db.places_RV.find().sort( { _id: 1 } )
{ "_id" : "a", "value" : { "location" : "Bishan", "batch" : 1 } }
{ "_id" : "b", "value" : { "location" : "Bukit Timah", "batch" : 1 } }
{ "_id" : "c", "value" : { "location" : "Ang Mo Kio", "batch" : 1 } }
{ "_id" : "d", "value" : { "location" : "Segar", "batch" : 1 } }
{ "_id" : "e", "value" : { "location" : "Fajar", "batch" : 1 } }
{ "_id" : "f", "value" : { "location" : "dover", "batch" : 2 } }
{ "_id" : "g", "value" : { "location" : "Buona Vista", "batch" : 2 } }
{ "_id" : "h", "value" : { "location" : "Marina Bay", "batch" : 2 } }
{ "_id" : "i", "value" : { "location" : "Rocher", "batch" : 2 } }
{ "_id" : "j", "value" : { "location" : "down town", "batch" : 2 } }
{ "_id" : "k", "value" : { "location" : "Jurong", "batch" : 3 } }
{ "_id" : "l", "value" : { "location" : "Pungol", "batch" : 3 } }
{ "_id" : "m", "value" : { "location" : "One North", "batch" : 3 } }
{ "_id" : "n", "value" : { "location" : "Cho Chu Kang", "batch" : 3 } }
{ "_id" : "o", "value" : { "location" : "Yishun", "batch" : 3 } }
Regards,
Rama