marks , . , MapReduce , JavaScript, parseInt(), . , .
1: ( )
, , . , mongodb find(), forEach() update() :
db.student.find({ "marks": { "$type": 2 } }).snapshot().forEach(function(doc) {
db.student.update(
{ "_id": doc._id, "marks": { "$type": 2 } },
{ "$set": { "marks": parseInt(doc.marks) } }
);
});
db , mongo bulk updates :
MongoDB >= 2.6 < 3,2:
var bulk = db.student.initializeUnorderedBulkOp(),
counter = 0;
db.student.find({"marks": {"$exists": true, "$type": 2 }}).forEach(function (doc) {
bulk.find({ "_id": doc._id }).updateOne({
"$set": { "marks": parseInt(doc.marks) }
});
counter++;
if (counter % 1000 === 0) {
bulk.execute();
bulk = db.student.initializeUnorderedBulkOp();
}
})
if (counter % 1000 !== 0) bulk.execute();
MongoDB 3.2 :
var ops = [],
cursor = db.student.find({"marks": {"$exists": true, "$type": 2 }});
cursor.forEach(function (doc) {
ops.push({
"updateOne": {
"filter": { "_id": doc._id } ,
"update": { "$set": { "marks": parseInt(doc.marks) } }
}
});
if (ops.length === 1000) {
db.student.bulkWrite(ops);
ops = [];
}
});
if (ops.length > 0) db.student.bulkWrite(ops);
2: MapReduce
- MapReduce, JavaScript parseInt().
MapReduce , . marks subject subject marks. JavaScript parseInt(). : this , :
var mapper = function () {
var x = parseInt(this.marks);
emit(this.subject, x);
};
keySubject valuesMarks. valuesMarks - , marks, keySubject.
valuesMarks .
var reducer = function(keySubject, valuesMarks) {
return Array.sum(valuesMarks);
};
db.student.mapReduce(
mapper,
reducer,
{
out : "example_results",
query: { subject : "maths" }
}
);
MapReduce db.example_results. , db.example_results.find() :
{
"_id" : "maths",
"value" : 163
}