I am trying to write a mapReduce query to find the car with the lowest value of price plus mileage for each manufacturer. I am fairly new to this and am not sure how to emit a pair of values(i.e Milage & Price) then reduce them to a single value.
var mapFunction = function () {
var key = this._id;
var values = [this.Milage, this.Price];
emit(key, values);
};
//Reducing failes here!
var reduceFunction = function (key, values) {
let reducedValue = 0;
values.forEach((num) => {
reducedValue += parseFloat(num);
});
return reducedValue;
};
lowestValuePerManufacturer = async () => {
const client = await MongoClient.connect(url, {
useNewUrlParser: true,
useUnifiedTopology: true,
}).catch((err) => console.log("Could not connect to MongoDB", err));
try {
const db = client.db(dbName);
const collection = db.collection(collectionName);
//Query starts here!
const res = await collection.mapReduce(mapFunction, reduceFunction, {
out: { inline: 1 },
});
console.log(res);
} catch (err) {
///
}
};
Data is an array of car objects as
{
"Manufacturer": "Fiat",
"Colour": "Black",
"Model": "Panda",
"Milage": 33292.0,
"Price": 2668.32,
"Classification": "Motor Cars",
"Extras": [
"SatNav",
"ABS"
]
},
$groupinstead of map/reduce: docs.mongodb.com/manual/core/map-reduce